/// <summary>
 /// Initializes a new instance of the <see cref="XLinearGradientBrush"/> class.
 /// </summary>
 public XLinearGradientBrush(XPoint point1, XPoint point2, XColor color1, XColor color2)
 {
   this.point1 = point1;
   this.point2 = point2;
   this.color1 = color1;
   this.color2 = color2;
 }
Exemple #2
0
 internal XPen(XColor color, double width, bool immutable)
 {
   this.color = color;
   this.width = width;
   this.lineJoin = XLineJoin.Miter;
   this.lineCap = XLineCap.Flat;
   this.dashStyle = XDashStyle.Solid;
   this.dashOffset = 0f;
   this.immutable = immutable;
 }
Exemple #3
0
 internal XPen(XColor color, double width, bool immutable)
 {
     _color = color;
     _width = width;
     _lineJoin = XLineJoin.Miter;
     _lineCap = XLineCap.Flat;
     _dashStyle = XDashStyle.Solid;
     _dashOffset = 0f;
     _immutable = immutable;
 }
Exemple #4
0
        static void Main()
        {
            const string watermark = "PDFsharp";
            const int    emSize    = 150;

            // Get a fresh copy of the sample PDF file
            const string filename = "Portable Document Format.pdf";

            File.Copy(Path.Combine("d:/WImageTest/PDFs/", filename),
                      Path.Combine(Directory.GetCurrentDirectory(), filename), true);

            // Create the font for drawing the watermark
            XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);

            // Open an existing document for editing and loop through its pages
            PdfDocument document = PdfReader.Open(filename);

            // Set version to PDF 1.4 (Acrobat 5) because we use transparency.
            if (document.Version < 14)
            {
                document.Version = 14;
            }

            for (int idx = 0; idx < document.Pages.Count; idx++)
            {
                //if (idx == 1) break;
                PdfPage page = document.Pages[idx];

                switch (idx % 3)
                {
                case 0:
                {
                    // Variation 1: Draw watermark as text string

                    // Get an XGraphics object for drawing beneath the existing content
                    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

#if true_
                    // Fill background with linear gradient color
                    XRect rect = page.MediaBox.ToXRect();
                    XLinearGradientBrush gbrush = new XLinearGradientBrush(rect,
                                                                           XColors.LightSalmon, XColors.WhiteSmoke, XLinearGradientMode.Vertical);
                    gfx.DrawRectangle(gbrush, rect);
#endif

                    // Get the size (in point) of the text
                    XSize size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a string format
                    XStringFormat format = new XStringFormat();
                    format.Alignment     = XStringAlignment.Near;
                    format.LineAlignment = XLineAlignment.Near;

                    // Create a dimmed red brush
                    XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));

                    // Draw the string
                    gfx.DrawString(watermark, font, brush,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   format);
                }
                break;

                case 1:
                {
                    // Variation 2: Draw watermark as outlined graphical path

                    // Get an XGraphics object for drawing beneath the existing content
                    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

                    // Get the size (in point) of the text
                    XSize size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a graphical path
                    XGraphicsPath path = new XGraphicsPath();

                    // Add the text to the path
                    path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   XStringFormats.Default());

                    // Create a dimmed red pen
                    XPen pen = new XPen(XColor.FromArgb(128, 255, 0, 0), 2);

                    // Stroke the outline of the path
                    gfx.DrawPath(pen, path);
                }
                break;

                case 2:
                {
                    // Variation 3: Draw watermark as transparent graphical path above text

                    // Get an XGraphics object for drawing above the existing content
                    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);

                    // Get the size (in point) of the text
                    XSize size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a graphical path
                    XGraphicsPath path = new XGraphicsPath();

                    // Add the text to the path
                    path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   XStringFormats.Default());

                    // Create a dimmed red pen and brush
                    XPen   pen   = new XPen(XColor.FromArgb(50, 75, 0, 130), 3);
                    XBrush brush = new XSolidBrush(XColor.FromArgb(50, 106, 90, 205));

                    // Stroke the outline of the path
                    gfx.DrawPath(pen, brush, path);
                }
                break;
                }
            }
            // Save the document...
            document.Save(filename);
            // ...and start a viewer
            Process.Start(filename);
        }
Exemple #5
0
 internal XSolidBrush(XColor color, bool immutable)
 {
   this.color = color;
   this.immutable = immutable;
 }
Exemple #6
0
        /// <summary>
        /// Tries to determine the Appearance of the Field by checking elements of its dictionary
        /// </summary>
        protected internal void DetermineAppearance()
        {
            try
            {
                var da = Elements.GetString(Keys.DA);     // 12.7.3.3
                if (String.IsNullOrEmpty(da))
                {
                    return;
                }
                string fontName = null;
                double fontSize = 0.0;
                var    content  = ContentReader.ReadContent(PdfEncoders.RawEncoding.GetBytes(da));
                for (var i = 0; i < content.Count; i++)
                {
                    var op = content[i] as COperator;
                    if (op != null)
                    {
                        switch (op.OpCode.OpCodeName)
                        {
                        case OpCodeName.Tf:
                            fontName = op.Operands[0].ToString();
                            fontSize = Double.Parse(op.Operands[1].ToString(), CultureInfo.InvariantCulture);
                            break;

                        case OpCodeName.g:              // gray value (0.0 = black, 1.0 = white)
                            if (op.Operands.Count > 0)
                            {
                                ForeColor = XColor.FromGrayScale(Double.Parse(op.Operands[0].ToString(), CultureInfo.InvariantCulture));
                            }
                            break;

                        case OpCodeName.rg:             // rgb color (Chapter 8.6.8)
                            if (op.Operands.Count > 2)
                            {
                                var r = Double.Parse(op.Operands[0].ToString(), CultureInfo.InvariantCulture);
                                var g = Double.Parse(op.Operands[1].ToString(), CultureInfo.InvariantCulture);
                                var b = Double.Parse(op.Operands[2].ToString(), CultureInfo.InvariantCulture);
                                ForeColor = XColor.FromArgb((int)(r * 255.0), (int)(g * 255.0), (int)(b * 255.0));
                            }
                            break;
                        }
                    }
                }
                if (!String.IsNullOrEmpty(fontName))
                {
                    ContentFontName = fontName;    // e.g. "/Helv"
                    var possibleResources = new[] { _document.AcroForm.Elements.GetDictionary(PdfAcroForm.Keys.DR), Elements.GetDictionary(PdfAcroForm.Keys.DR) };
                    foreach (var resources in possibleResources)
                    {
                        if (resources != null && resources.Elements.ContainsKey("/Font"))
                        {
                            var fontList = resources.Elements.GetDictionary("/Font");
                            var fontRef  = fontList.Elements.GetReference(fontName);
                            if (fontRef != null)
                            {
                                var fontDict = fontRef.Value as PdfDictionary;
                                if (fontDict != null && fontDict.Elements.ContainsKey("/BaseFont"))
                                {
                                    var baseName = fontDict.Elements.GetString("/BaseFont");
                                    if (!String.IsNullOrEmpty(baseName))
                                    {
                                        fontName = baseName; // e.g. "/Helvetica"
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    BaseContentFontName = fontName.Substring(1);
                    // 12.7.3.3 :   A zero value for size means that the font shall be auto-sized: its size
                    //              shall be computed as a function of the height of the annotation rectangle.
                    if (fontSize < 1.0)
                    {
                        for (var a = 0; a < Annotations.Elements.Count; a++)
                        {
                            var widget = Annotations.Elements[a];
                            if (widget != null && !widget.Rectangle.IsEmpty)
                            {
                                var refValue = widget.Rotation == 0 || widget.Rotation == 180 || (widget.Flags & PdfAnnotationFlags.NoRotate) != 0 ? widget.Rectangle.Height : widget.Rectangle.Width;
                                if (!(this is PdfTextField) || !((PdfTextField)this).MultiLine)
                                {
                                    fontSize = refValue * 0.8;
                                }
                                if (fontSize > 1.0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    // When the field's font is one of the standard fonts, use WinAnsiEncoding, as that seems to work best with the tested documents
                    if (IsStandardFont(BaseContentFontName))
                    {
                        font = new XFont(BaseContentFontName.TrimStart('/'), Math.Max(1.0, fontSize), XFontStyle.Regular, new XPdfFontOptions(PdfFontEncoding.WinAnsi))
                        {
                            FromDocument = true, DocumentFontName = ContentFontName
                        }
                    }
                    ;
                    else
                    {
                        // ok, we bite the bullet and embed a new font (so at least the correct characters should show up, although with the possibly wrong font)
                        // TODO: Reasearch how to get the correct glyph indices for embedded fonts
                        font = new XFont(BaseContentFontName.TrimStart('/'), Math.Max(1.0, fontSize), GetFontStyle(BaseContentFontName));     // Avoid Exception, if size is zero
                    }
                }
            }
            catch
            {
                font = new XFont("Arial", 10);
            }
        }
        public void RealizePen(XPen pen, PdfColorMode colorMode)
        {
            const string frmt2     = Config.SignificantFigures2;
            const string format    = Config.SignificantFigures3;
            XColor       color     = pen.Color;
            bool         overPrint = pen.Overprint;

            color = ColorSpaceHelper.EnsureColorMode(colorMode, color);

            if (_realizedLineWith != pen._width)
            {
                _renderer.AppendFormatArgs("{0:" + format + "} w\n", pen._width);
                _realizedLineWith = pen._width;
            }

            if (_realizedLineCap != (int)pen._lineCap)
            {
                _renderer.AppendFormatArgs("{0} J\n", (int)pen._lineCap);
                _realizedLineCap = (int)pen._lineCap;
            }

            if (_realizedLineJoin != (int)pen._lineJoin)
            {
                _renderer.AppendFormatArgs("{0} j\n", (int)pen._lineJoin);
                _realizedLineJoin = (int)pen._lineJoin;
            }

            if (_realizedLineCap == (int)XLineJoin.Miter)
            {
                if (_realizedMiterLimit != (int)pen._miterLimit && (int)pen._miterLimit != 0)
                {
                    _renderer.AppendFormatInt("{0} M\n", (int)pen._miterLimit);
                    _realizedMiterLimit = (int)pen._miterLimit;
                }
            }

            if (_realizedDashStyle != pen._dashStyle || pen._dashStyle == XDashStyle.Custom)
            {
                double dot  = pen.Width;
                double dash = 3 * dot;

                // Line width 0 is not recommended but valid.
                XDashStyle dashStyle = pen.DashStyle;
                if (dot == 0)
                {
                    dashStyle = XDashStyle.Solid;
                }

                switch (dashStyle)
                {
                case XDashStyle.Solid:
                    _renderer.Append("[]0 d\n");
                    break;

                case XDashStyle.Dash:
                    _renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
                    break;

                case XDashStyle.Dot:
                    _renderer.AppendFormatArgs("[{0:" + frmt2 + "}]0 d\n", dot);
                    break;

                case XDashStyle.DashDot:
                    _renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
                    break;

                case XDashStyle.DashDotDot:
                    _renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
                    break;

                case XDashStyle.Custom:
                {
                    StringBuilder pdf = new StringBuilder("[", 256);
                    int           len = pen._dashPattern == null ? 0 : pen._dashPattern.Length;
                    for (int idx = 0; idx < len; idx++)
                    {
                        if (idx > 0)
                        {
                            pdf.Append(' ');
                        }
                        pdf.Append(PdfEncoders.ToString(pen._dashPattern[idx] * pen._width));
                    }
                    // Make an even number of values look like in GDI+
                    if (len > 0 && len % 2 == 1)
                    {
                        pdf.Append(' ');
                        pdf.Append(PdfEncoders.ToString(0.2 * pen._width));
                    }
                    pdf.AppendFormat(CultureInfo.InvariantCulture, "]{0:" + format + "} d\n", pen._dashOffset * pen._width);
                    string pattern = pdf.ToString();

                    // BUG: [email protected] reported a realizing problem
                    // HACK: I remove the if clause
                    //if (_realizedDashPattern != pattern)
                    {
                        _realizedDashPattern = pattern;
                        _renderer.Append(pattern);
                    }
                }
                break;
                }
                _realizedDashStyle = dashStyle;
            }

            if (colorMode != PdfColorMode.Cmyk)
            {
                if (_realizedStrokeColor.Rgb != color.Rgb)
                {
                    _renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Rgb));
                    _renderer.Append(" RG\n");
                }
            }
            else
            {
                if (!ColorSpaceHelper.IsEqualCmyk(_realizedStrokeColor, color))
                {
                    _renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Cmyk));
                    _renderer.Append(" K\n");
                }
            }

            if (_renderer.Owner.Version >= 14 && (_realizedStrokeColor.A != color.A || _realizedStrokeOverPrint != overPrint))
            {
                PdfExtGState extGState = _renderer.Owner.ExtGStateTable.GetExtGStateStroke(color.A, overPrint);
                string       gs        = _renderer.Resources.AddExtGState(extGState);
                _renderer.AppendFormatString("{0} gs\n", gs);

                // Must create transparency group.
                if (_renderer._page != null && color.A < 1)
                {
                    _renderer._page.TransparencyUsed = true;
                }
            }
            _realizedStrokeColor     = color;
            _realizedStrokeOverPrint = overPrint;
        }
        public static bool CopyPDF(string inputFolder, List <string> filesToCopy, List <string> watermarks, string outputFolder, string orderNumber = "", string jobName = "")
        {
            // copy pdf file(s) from input folder to output folder and stamp them with a watermark.  If there is more than one file in the list, they are combined into one,
            //  with the filename matching the name of the first file to copy.  There needs to be an equal amount of files and watermarks passed in.
            try
            {
                if (filesToCopy.Count != watermarks.Count)
                {
                    return(false);
                }

                PdfDocument outputDocument = new PdfDocument();
                PdfDocument inputDocument  = new PdfDocument();
                PdfDocument editedDocument = new PdfDocument();

                XUnit          height         = new XUnit();
                XUnit          width          = new XUnit();
                List <XUnit[]> xUnitArrayList = new List <XUnit[]>();

                int fileCount = 0;
                foreach (string fileName in filesToCopy)
                {
                    string inputPdfName = inputFolder + fileName;
                    xUnitArrayList.Clear();
                    if (File.Exists(inputPdfName))
                    {
                        inputDocument = PdfReader.Open(inputPdfName, PdfDocumentOpenMode.Modify);

                        int count = inputDocument.PageCount;
                        for (int idx = 0; idx < count; idx++)
                        {
                            PdfPage page          = inputDocument.Pages[idx];
                            PdfPage watermarkPage = new PdfPage(inputDocument);

                            // store page width and height in array list so we can reference again when we are producing output
                            height = page.Height;
                            width  = page.Width;
                            watermarkPage.Height = page.Height;
                            watermarkPage.Width  = page.Width;

                            XUnit[] pageDims = new XUnit[] { page.Height, page.Width };
                            xUnitArrayList.Add(pageDims);       // drawing page
                            xUnitArrayList.Add(pageDims);       // watermark page

                            XGraphics gfx = XGraphics.FromPdfPage(watermarkPage, XGraphicsPdfPageOptions.Prepend);

                            XFont          font = new XFont("Times New Roman", 15, XFontStyle.Bold);
                            XTextFormatter tf   = new XTextFormatter(gfx);

                            XRect  rect  = new XRect(40, 75, width - 40, height - 75);
                            XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
                            tf.DrawString(watermarks[fileCount], font, brush, rect, XStringFormats.TopLeft);

                            //inputDocument.AddPage(watermarkPage);
                            inputDocument.InsertPage(idx * 2 + 1, watermarkPage);
                        }

                        string randomFileName = Path.GetTempFileName();
                        inputPdfName = randomFileName;
                        inputDocument.Save(randomFileName);


                        editedDocument = PdfReader.Open(randomFileName, PdfDocumentOpenMode.Import);

                        // Iterate pages
                        count = editedDocument.PageCount;
                        for (int idx = 0; idx < count; idx++)
                        {
                            // Get the page from the external document...
                            PdfPage editedPage = editedDocument.Pages[idx];

                            XUnit[] outputPageDims = xUnitArrayList[idx];
                            editedPage.Height = outputPageDims[0];
                            editedPage.Width  = outputPageDims[1];

                            // ...and add it to the output document.
                            outputDocument.AddPage(editedPage);
                        }
                    }

                    if (!File.Exists(inputPdfName))
                    {
                        watermarks[fileCount] = "No Drawing Found For:\n" + watermarks[fileCount];

                        string randomFileName = Path.GetTempFileName();
                        inputPdfName = randomFileName;

                        // Create a new PDF document
                        PdfDocument document = new PdfDocument();
                        document.Info.Title = "Created with PDFsharp";

                        // Create an empty page
                        PdfPage page     = document.AddPage();
                        PdfPage pageBack = document.AddPage();
                        page.Orientation     = PageOrientation.Landscape;
                        pageBack.Orientation = PageOrientation.Landscape;

                        height = page.Height;
                        width  = page.Width;

                        // Get an XGraphics object for drawing
                        XGraphics gfx = XGraphics.FromPdfPage(page);

                        // Create a font
                        XFont font = new XFont("Times New Roman", 15, XFontStyle.Bold);

                        // Create point for upper-left corner of drawing.
                        PointF Line1Point = new PointF(50.0F, 50.0F);
                        PointF Line2Point = new PointF(50.0F, 70.0F);
                        PointF Line3Point = new PointF(50.0F, 90.0F);
                        PointF Line4Point = new PointF(50.0F, 110.0F);
                        PointF Line5Point = new PointF(50.0F, 130.0F);

                        XBrush         brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
                        XTextFormatter tf    = new XTextFormatter(gfx);
                        XRect          rect  = new XRect(40, 75, width - 40, height - 75);

                        tf.DrawString(watermarks[fileCount], font, brush, rect, XStringFormats.TopLeft);

                        // Save the document...
                        string newPDFName = inputPdfName;
                        document.Save(newPDFName);

                        inputDocument = PdfReader.Open(newPDFName, PdfDocumentOpenMode.Import);

                        // Iterate pages
                        int count = inputDocument.PageCount;
                        for (int idx = 0; idx < count; idx++)
                        {
                            // Get the page from the external document...
                            page = inputDocument.Pages[idx];

                            // ...and add it to the output document.
                            outputDocument.AddPage(page);
                        }
                    }
                    fileCount++;
                }


                bool successfulPrint = false;
                do
                {
                    try
                    {
                        // Save the document...
                        string outputFileName = "";
                        if (orderNumber == "")
                        {
                            outputFileName = outputFolder + filesToCopy[0];
                        }
                        else
                        {
                            if (outputFolder.Contains("Batch") || inputFolder.Contains("batch"))
                            {
                                outputFileName = outputFolder + "\\" + orderNumber + "-" + filesToCopy[0];
                            }
                            else
                            {
                                outputFileName = outputFolder + "\\" + orderNumber + "-" + jobName + ".pdf";
                            }
                        }

                        outputDocument.Save(outputFileName);
                        successfulPrint = true;
                    }
                    catch (Exception ex)
                    {
                        DialogResult result = MessageBox.Show("Problem in printing PDF for " + jobName + "\n" + "The file name may have an invalid character or the file may be open in Windows Explorer. Please close it and click OK to try again.  If you cancel, the drawing will not get printed.", "Confirm", MessageBoxButtons.RetryCancel);
                        if (result == DialogResult.Cancel)
                        {
                            successfulPrint = true;
                        }
                        ;
                    }
                } while (!successfulPrint);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemple #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XPen"/> class.
 /// </summary>
 public XPen(XColor color, double width)
   : this(color, width, false)
 { }
Exemple #10
0
        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("RAE_{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 = "Adverse Event Report for " + DateTime.Now.ToString("yyyy-MM-dd hh:MM");
            gfx.DrawString("Adverse Event 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("Filter", fontb, XBrushes.Black, new XRect(columnPosition, linePosition, page.Width.Point, 20), XStringFormats.TopLeft);
            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("Adverse Event 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 * 5);
                            headerArray.Add(cell.Text);

                            gfx.DrawString(cell.Text, fontb, XBrushes.Black, new XRect(columnPosition, linePosition, cell.Width.Value * 5, 20), XStringFormats.TopLeft);
                            columnPosition += (int)cell.Width.Value * 5;
                        }
                        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();
        }
Exemple #11
0
 internal XSolidBrush(XColor color, bool immutable)
 {
     _color = color;
     _immutable = immutable;
 }
Exemple #12
0
 public static bool OnDrawString(XSpriteBatch __instance, SpriteFont spriteFont, StringBuilder text, XVector2 position, XColor color)
 {
     __instance.DrawString(
         spriteFont: spriteFont,
         text: text,
         position: position,
         color: color,
         rotation: 0.0f,
         origin: XVector2.Zero,
         scale: XVector2.One,
         effects: SpriteEffects.None,
         layerDepth: 0.0f
         );
     return(false);
 }
Exemple #13
0
        public static XBrush ToXBrush(this TextStyle textStyle)
        {
            var color = XColor.FromArgb(textStyle.Brush.ToArgb());

            return(new XSolidBrush(color));
        }
        /// <summary>
        /// Writes a Glyphs to the content stream.
        /// </summary>
        private void WriteGlyphs(Glyphs glyphs)
        {
            WriteSaveState("begin Glyphs", glyphs.Name);

            // Transform also affects clipping and opacity mask
            bool transformed = glyphs.RenderTransform != null &&
                               !glyphs.RenderTransform.Value.IsIdentity;

            if (transformed)
            {
                WriteRenderTransform(glyphs.RenderTransform.Value);
            }

            bool clipped = glyphs.Clip != null;

            if (clipped)
            {
                WriteClip(glyphs.Clip);
            }

            if (glyphs.Opacity < 1)
            {
                MultiplyOpacity(glyphs.Opacity);
            }

            if (glyphs.OpacityMask != null)
            {
                WriteOpacityMask(glyphs.OpacityMask);
            }

            XMatrix textMatrix = new XMatrix();

            textMatrix.TranslatePrepend(glyphs.OriginX, glyphs.OriginY);
            glyphs.OriginX = glyphs.OriginY = 0; // HACK: do not change model

            double emSize = glyphs.FontRenderingEmSize;

            textMatrix.ScalePrepend(glyphs.FontRenderingEmSize);
            glyphs.FontRenderingEmSize = 1; // HACK: do not change model


            bool boldSimulation =
                (glyphs.StyleSimulations & StyleSimulations.BoldSimulation)
                == StyleSimulations.BoldSimulation;

            // just a draft...
            if (boldSimulation)
            {
                boldSimulation = true;

                // draw black stroke if it is not a solid color brush
                XColor color = XColor.FromArgb(0, 0, 0);
                if (glyphs.Fill is SolidColorBrush)
                {
                    var brush = glyphs.Fill as SolidColorBrush;
                    color = brush.Color.ToXColor();
                }
                WriteLiteral(String.Format(CultureInfo.InvariantCulture, "{0:0.###} {1:0.###} {2:0.###}  RG\n", color.R / 255.0, color.G / 255.0, color.B / 255.0));
                WriteLiteral("{0:0.###} w\n", emSize / 50);
            }

            if ((glyphs.StyleSimulations & StyleSimulations.ItalicSimulation)
                == StyleSimulations.ItalicSimulation)
            {
                textMatrix.SkewPrepend(-20, 0);
            }

            XForm  xform  = null;
            XImage ximage = null;

            RealizeFill(glyphs.Fill, ref xform, ref ximage);
            RealizeFont(glyphs);

            if (boldSimulation)
            {
                WriteLiteral("2 Tr\n", 1);
            }

            double x = glyphs.OriginX;
            double y = glyphs.OriginY;


            //switch (format.Alignment)
            //{
            //  case XStringAlignment.Near:
            //    // nothing to do
            //    break;

            //  case XStringAlignment.Center:
            //    x += (rect.Width - width) / 2;
            //    break;

            //  case XStringAlignment.Far:
            //    x += rect.Width - width;
            //    break;
            //}

            PdfFont realizedFont = this.graphicsState.realizedFont;

            Debug.Assert(realizedFont != null);
            realizedFont.AddChars(glyphs.UnicodeString);

            OpenTypeDescriptor descriptor = realizedFont.FontDescriptor.descriptor;

            //if (bold && !descriptor.IsBoldFace)
            //{
            //  // TODO: emulate bold by thicker outline
            //}

            //if (italic && !descriptor.IsBoldFace)
            //{
            //  // TODO: emulate italic by shearing transformation
            //}

#if true
            string s2 = "";
            string s  = glyphs.UnicodeString;
            if (!String.IsNullOrEmpty(s))
            {
                int length = s.Length;
                for (int idx = 0; idx < length; idx++)
                {
                    char ch      = s[idx];
                    int  glyphID = 0;
                    if (descriptor.fontData.cmap.symbol)
                    {
                        glyphID = (int)ch + (descriptor.fontData.os2.usFirstCharIndex & 0xFF00);
                        glyphID = descriptor.CharCodeToGlyphIndex((char)glyphID);
                    }
                    else
                    {
                        glyphID = descriptor.CharCodeToGlyphIndex(ch);
                    }
                    s2 += (char)glyphID;
                }
            }
            s = s2;
#endif

            byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s);
            bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null);
            string text = PdfEncoders.RawEncoding.GetString(bytes);
            if (glyphs.IsSideways)
            {
                textMatrix.RotateAtPrepend(-90, new XPoint(x, y));
                XPoint pos = new XPoint(x, y);
                AdjustTextMatrix(ref pos);
                //WriteTextTransform(textMatrix);
                WriteLiteral("{0} Tj\n", text);
            }
            else
            {
#if true
                //if (glyphs.BidiLevel % 2 == 1)
                //  WriteLiteral("-1 Tc\n");

                if (!textMatrix.IsIdentity)
                {
                    WriteTextTransform(textMatrix);
                }

                WriteGlyphsInternal(glyphs, null);
#else
                XPoint pos = new XPoint(x, y);
                AdjustTextMatrix(ref pos);
                WriteLiteral("{0:0.###} {1:0.###} Td {2} Tj\n", pos.x, pos.y, text);
                //PdfEncoders.ToStringLiteral(s, PdfStringEncoding.RawEncoding, null));
#endif
            }
            WriteRestoreState("end Glyphs", glyphs.Name);
        }
Exemple #15
0
        public static XColor ToXColor(this Color color)
        {
            var c = XColor.FromArgb(color.ToArgb());

            return(c);
        }
        public static bool AddWatermark(string fileName, string watermark)
        {
            try
            {
                PdfDocument outputDocument = new PdfDocument();
                PdfDocument inputDocument  = new PdfDocument();
                PdfDocument editedDocument = new PdfDocument();

                XUnit          height         = new XUnit();
                XUnit          width          = new XUnit();
                List <XUnit[]> xUnitArrayList = new List <XUnit[]>();

                string inputPdfName = fileName;
                xUnitArrayList.Clear();
                if (File.Exists(inputPdfName))
                {
                    inputDocument = PdfReader.Open(inputPdfName, PdfDocumentOpenMode.Modify);

                    int count = inputDocument.PageCount;
                    for (int idx = 0; idx < count; idx++)
                    {
                        PdfPage page = inputDocument.Pages[idx];
                        // store page width and height in array list so we can reference again when we are producing output
                        height = page.Height;
                        width  = page.Width;
                        XUnit[] pageDims = new XUnit[] { page.Height, page.Width };
                        xUnitArrayList.Add(pageDims);       // drawing page
                        xUnitArrayList.Add(pageDims);       // watermark page

                        PdfPage watermarkPage = new PdfPage(inputDocument);
                        watermarkPage.Height = page.Height;
                        watermarkPage.Width  = page.Width;

                        XGraphics gfx = XGraphics.FromPdfPage(watermarkPage, XGraphicsPdfPageOptions.Prepend);

                        XFont          font = new XFont("Times New Roman", 15, XFontStyle.Bold);
                        XTextFormatter tf   = new XTextFormatter(gfx);

                        XRect  rect  = new XRect(40, 75, width - 40, height - 75);
                        XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
                        tf.DrawString(watermark, font, brush, rect, XStringFormats.TopLeft);

                        //inputDocument.AddPage(watermarkPage);
                        inputDocument.InsertPage(idx * 2 + 1, watermarkPage);
                    }

                    string randomFileName = Path.GetTempFileName();
                    inputPdfName = randomFileName;
                    inputDocument.Save(randomFileName);


                    editedDocument = PdfReader.Open(randomFileName, PdfDocumentOpenMode.Import);

                    // Iterate pages
                    count = editedDocument.PageCount;
                    for (int idx = 0; idx < count; idx++)
                    {
                        // Get the page from the external document...
                        PdfPage editedPage = editedDocument.Pages[idx];

                        XUnit[] outputPageDims = xUnitArrayList[idx];
                        editedPage.Height = outputPageDims[0];
                        editedPage.Width  = outputPageDims[1];

                        // ...and add it to the output document.
                        outputDocument.AddPage(editedPage);
                    }

                    // save the watermarked file
                    outputDocument.Save(fileName);
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #17
0
        public void WorldColors(World world, out XColor penColorOut, out XColor brushColorOut)
        {
            Color penColor = Color.Empty;
            Color brushColor = Color.Empty;

            if (showWorldDetailColors)
            {
                if (world.IsAg && world.IsRi)
                {
                    penColor = brushColor = Color.Gold;
                }
                else if (world.IsAg)
                {
                    penColor = brushColor = Color.Green;
                }
                else if (world.IsRi)
                {
                    penColor = brushColor = Color.Purple;
                }
                else if (world.IsIn)
                {
                    penColor = brushColor = Color.FromArgb(0x88, 0x88, 0x88); // Gray
                }
                else if (world.Atmosphere > 10)
                {
                    penColor = brushColor = Color.FromArgb(0xcc, 0x66, 0x26); // Rust
                }
                else if (world.IsVa)
                {
                    brushColor = Color.Black;
                    penColor = Color.White;
                }
                else if (world.WaterPresent)
                {
                    brushColor = worldWater.fillColor;
                    penColor = worldWater.pen.color;
                }
                else
                {
                    brushColor = worldNoWater.fillColor;
                    penColor = worldNoWater.pen.color;
                }
            }
            else
            {
                // Classic colors

                // World disc
                brushColor = (world.WaterPresent) ? worldWater.fillColor : worldNoWater.fillColor;
                penColor = (world.WaterPresent) ? worldWater.pen.color : worldNoWater.pen.color;
            }

            penColorOut = penColor.IsEmpty ? XColor.Empty : penColor;
            brushColorOut = brushColor.IsEmpty ? XColor.Empty : brushColor;
        }
Exemple #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            PdfDocument doc = new PdfDocument();

            doc.Info.Title = "Created with PDFsharp";


            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();
            XGraphics   gfx      = XGraphics.FromPdfPage(page);
            XFont       font     = new XFont("Times New Roman", 8, XFontStyle.Bold);
            XPen        pen      = new XPen(XColors.Black, 0.8);

            gfx.DrawRectangle(pen, 75, 70, 150, 65);
            gfx.DrawRectangle(pen, 400, 70, 125, 65);

            gfx.DrawString("Lycée Pasteur Mont Roland", font, XBrushes.Black, 100, 80);
            gfx.DrawString("Enseignement Supérieur", font, XBrushes.Black, 107, 90);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("9 avenue Rockefeller", font, XBrushes.Black, 117, 100);
            gfx.DrawString("BP 24", font, XBrushes.Black, 139, 110);
            gfx.DrawString("39107 Dole Cedex", font, XBrushes.Black, 120, 120);
            gfx.DrawString("03 84 79 75 00", font, XBrushes.Black, 127, 130);
            gfx.DrawString("En partenariat avec :", font, XBrushes.Black, 429, 80);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("CFA ASPECT", font, XBrushes.Black, 438, 100);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("20 rue Megevand", font, XBrushes.Black, 435, 110);
            gfx.DrawString("25041 Besançon", font, XBrushes.Black, 436, 120);
            gfx.DrawString("03 81 25 03 75", font, XBrushes.Black, 439, 130);
            gfx.DrawImage(XImage.FromFile("lpmr.png"), 230, 75, 80, 50);
            gfx.DrawImage(XImage.FromFile("aspect.jpg"), 318, 75, 80, 50);
            font = new XFont("Times New Roman", 10, XFontStyle.Bold);
            gfx.DrawString("RELEVE DE NOTES - Promotion 2019 2021 - Première année", font, XBrushes.Black, 184, 160);
            gfx.DrawString("Administrateur de Systèmes d'Information", font, XBrushes.Black, 222, 180);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("TITRE RNCP de Niveau 6 - N° de certification 26E32601 - Code NSF 326 n", font, XBrushes.Black, 186, 195);

            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawString("Nom de l'apprenti : DIZIERE Emma", font, XBrushes.Black, 90, 220);
            pen = new XPen(XColors.Black, 1);
            XBrush brush = new XSolidBrush(XColor.FromArgb(240, 240, 240));

            gfx.DrawRectangle(pen, brush, 50, 225, 450, 15);
            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Envaluation au sein du centre de formation ", font, XBrushes.Black, 228, 235);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 50, 240, 105, 20);

            gfx.DrawString("Matières ", font, XBrushes.Black, 60, 252);
            gfx.DrawRectangle(pen, 155, 240, 180, 10);

            gfx.DrawString("Moyennes sur 20", font, XBrushes.Black, 222, 248);

            gfx.DrawString("Coef", font, XBrushes.Black, 164, 258);
            gfx.DrawRectangle(pen, 191, 250, 36, 10);
            gfx.DrawString("Ctrl Cont", font, XBrushes.Black, 194, 258);
            gfx.DrawRectangle(pen, 227, 250, 36, 10);
            gfx.DrawString("Examen", font, XBrushes.Black, 232, 258);
            gfx.DrawRectangle(pen, 263, 250, 36, 10);
            gfx.DrawString("Total", font, XBrushes.Black, 272, 258);
            gfx.DrawRectangle(pen, 299, 250, 36, 10);
            gfx.DrawString("Classe", font, XBrushes.Black, 307, 258);
            gfx.DrawRectangle(pen, 335, 240, 165, 20);
            gfx.DrawString("Notes sur 20", font, XBrushes.Black, 395, 255);

            gfx.DrawString("1", font, XBrushes.Black, 164, 268);
            gfx.DrawRectangle(pen, 155, 260, 180, 10);
            gfx.DrawRectangle(pen, 155, 260, 36, 10);
            gfx.DrawRectangle(pen, 227, 260, 36, 10);
            gfx.DrawRectangle(pen, 263, 260, 36, 10);
            gfx.DrawString("Anglais Professionel ", font, XBrushes.Black, 55, 268);
            gfx.DrawRectangle(pen, 50, 260, 450, 10);

            gfx.DrawString("1", font, XBrushes.Black, 164, 278);
            gfx.DrawRectangle(pen, 155, 270, 180, 10);
            gfx.DrawRectangle(pen, 155, 270, 36, 10);
            gfx.DrawRectangle(pen, 227, 270, 36, 10);
            gfx.DrawRectangle(pen, 263, 270, 36, 10);
            gfx.DrawString("Outil mathématique", font, XBrushes.Black, 55, 278);
            gfx.DrawRectangle(pen, 50, 270, 450, 10);

            gfx.DrawString("1", font, XBrushes.Black, 164, 288);
            gfx.DrawRectangle(pen, 155, 280, 180, 10);
            gfx.DrawRectangle(pen, 155, 280, 36, 10);
            gfx.DrawRectangle(pen, 227, 280, 36, 10);
            gfx.DrawRectangle(pen, 263, 280, 36, 10);
            gfx.DrawString("Droit informatique ", font, XBrushes.Black, 55, 288);
            gfx.DrawRectangle(pen, 50, 280, 450, 10);

            gfx.DrawString("2", font, XBrushes.Black, 164, 298);
            gfx.DrawRectangle(pen, 155, 290, 180, 10);
            gfx.DrawRectangle(pen, 155, 290, 36, 10);
            gfx.DrawRectangle(pen, 227, 290, 36, 10);
            gfx.DrawRectangle(pen, 263, 290, 36, 10);
            gfx.DrawString("Management Budgetisation", font, XBrushes.Black, 55, 298);
            gfx.DrawRectangle(pen, 50, 290, 450, 10);
            gfx.DrawString("Evalué en première année ", font, XBrushes.Black, 370, 298);

            gfx.DrawString("3", font, XBrushes.Black, 164, 308);
            gfx.DrawRectangle(pen, 155, 300, 180, 10);
            gfx.DrawRectangle(pen, 155, 300, 36, 10);
            gfx.DrawRectangle(pen, 227, 300, 36, 10);
            gfx.DrawRectangle(pen, 263, 300, 36, 10);
            gfx.DrawString("Génie Logiciel ", font, XBrushes.Black, 55, 308);
            gfx.DrawRectangle(pen, 50, 300, 450, 10);

            gfx.DrawString("3", font, XBrushes.Black, 164, 318);
            gfx.DrawRectangle(pen, 155, 310, 180, 10);
            gfx.DrawRectangle(pen, 155, 310, 36, 10);
            gfx.DrawRectangle(pen, 227, 310, 36, 10);
            gfx.DrawRectangle(pen, 263, 310, 36, 10);
            gfx.DrawString("Réseaux, Systèmes et Sécurité ", font, XBrushes.Black, 55, 318);
            gfx.DrawRectangle(pen, 50, 310, 450, 10);

            gfx.DrawString("1", font, XBrushes.Black, 164, 328);
            gfx.DrawRectangle(pen, 155, 320, 180, 10);
            gfx.DrawRectangle(pen, 155, 320, 36, 10);
            gfx.DrawRectangle(pen, 227, 320, 36, 10);
            gfx.DrawRectangle(pen, 263, 320, 36, 10);
            gfx.DrawString("BD ", font, XBrushes.Black, 55, 328);
            gfx.DrawRectangle(pen, 50, 320, 450, 10);
            gfx.DrawString("Evalué en projet tutoré", font, XBrushes.Black, 370, 328);

            gfx.DrawString("3", font, XBrushes.Black, 164, 338);
            gfx.DrawRectangle(pen, 155, 330, 180, 10);
            gfx.DrawRectangle(pen, 155, 330, 36, 10);
            gfx.DrawRectangle(pen, 227, 330, 36, 10);
            gfx.DrawRectangle(pen, 263, 330, 36, 10);
            gfx.DrawString("Conduite de Projet ", font, XBrushes.Black, 55, 338);
            gfx.DrawRectangle(pen, 50, 330, 450, 10);
            gfx.DrawString("Evalué en première année ", font, XBrushes.Black, 370, 338);

            gfx.DrawString("3", font, XBrushes.Black, 164, 348);
            gfx.DrawRectangle(pen, 155, 340, 180, 10);
            gfx.DrawRectangle(pen, 155, 340, 36, 10);
            gfx.DrawRectangle(pen, 227, 340, 36, 10);
            gfx.DrawRectangle(pen, 263, 340, 36, 10);
            gfx.DrawString("Projet Tutoré ", font, XBrushes.Black, 55, 348);
            gfx.DrawRectangle(pen, 50, 340, 450, 10);
            gfx.DrawString("Evalué en deuxième année ", font, XBrushes.Black, 370, 348);


            gfx.DrawString("Moyenne", font, XBrushes.Black, 164, 358);
            gfx.DrawRectangle(pen, 50, 350, 450, 10);
            gfx.DrawRectangle(pen, 263, 350, 36, 10);
            gfx.DrawRectangle(pen, 299, 350, 36, 10);
            gfx.DrawString("Moyenne informatique ", font, XBrushes.Black, 360, 358);
            gfx.DrawRectangle(pen, 450, 350, 50, 10);

            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Evaluation en entreprise", font, XBrushes.Black, 228, 378);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 50, 370, 450, 10);
            gfx.DrawString("Livret de Suivi", font, XBrushes.Black, 80, 388);
            gfx.DrawString("12", font, XBrushes.Black, 164, 388);
            gfx.DrawRectangle(pen, 50, 380, 450, 10);
            gfx.DrawRectangle(pen, 155, 380, 180, 10);
            gfx.DrawRectangle(pen, 155, 380, 36, 10);
            gfx.DrawRectangle(pen, 263, 380, 36, 10);

            gfx.DrawString("Projet Entreprise", font, XBrushes.Black, 80, 398);
            gfx.DrawRectangle(pen, 50, 390, 450, 10);
            gfx.DrawRectangle(pen, 155, 390, 180, 10);
            gfx.DrawRectangle(pen, 155, 390, 36, 10);
            gfx.DrawRectangle(pen, 263, 390, 36, 10);

            gfx.DrawString("Moyenne", font, XBrushes.Black, 164, 408);
            gfx.DrawRectangle(pen, 50, 400, 450, 10);
            gfx.DrawRectangle(pen, 263, 400, 36, 10);
            gfx.DrawRectangle(pen, 299, 400, 36, 10);

            font = new XFont("Times New Roman", 8, XFontStyle.Bold);
            gfx.DrawString("Appréciation du conseil de promotion et du responsable de dispositif", font, XBrushes.Black, 198, 428);
            pen  = new XPen(XColors.Black, 0.8);
            font = new XFont("Times New Roman", 8, XFontStyle.Regular);
            gfx.DrawRectangle(pen, 50, 420, 450, 10);
            gfx.DrawRectangle(pen, 50, 430, 450, 100);


            gfx.DrawString("Rappel Moyenne année 1", font, XBrushes.Black, 134, 448);
            gfx.DrawRectangle(pen, 284, 440, 30, 10);

            gfx.DrawString("Moyenne année 2 1er semestre", font, XBrushes.Black, 134, 458);
            gfx.DrawRectangle(pen, 284, 450, 30, 10);

            gfx.DrawString("A Dole le 10 mars 2021 ", font, XBrushes.Black, 290, 470);
            gfx.DrawString("Le responsable de dispositif : Julian COURBEZ", font, XBrushes.Black, 290, 480);


            const string filename = "Bulletin-notes-1annee.pdf";

            document.Save(filename);

            Process.Start(filename);
        }
Exemple #19
0
 public ColorItem(XColor color, string name)
 {
     Color = color;
     Name = name;
 }
Exemple #20
0
        public static void Run()
        {
            const string watermark = "PDFsharp";
            const int    emSize    = 150;

            // Get a fresh copy of the sample PDF file.
            const string filename = "Portable Document Format.pdf";
            var          file     = Path.Combine(Directory.GetCurrentDirectory(), filename);

            File.Copy(Path.Combine("assets", filename), file, true);

            // Remove ReadOnly attribute from the copy.
            File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);

            // Create the font for drawing the watermark.
            var font = new XFont(FontNames.Arial, emSize, XFontStyle.BoldItalic);

            // Open an existing document for editing and loop through its pages.
            var document = PdfReader.Open(filename);

            // Set version to PDF 1.4 (Acrobat 5) because we use transparency.
            if (document.Version < 14)
            {
                document.Version = 14;
            }

            for (var idx = 0; idx < document.Pages.Count; idx++)
            {
                var page = document.Pages[idx];

                switch (idx % 3)
                {
                case 0:
                {
                    // Variation 1: Draw a watermark as a text string.

                    // Get an XGraphics object for drawing beneath the existing content.
                    var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

                    // Get the size (in points) of the text.
                    var size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page.
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a string format.
                    var format = new XStringFormat();
                    format.Alignment     = XStringAlignment.Near;
                    format.LineAlignment = XLineAlignment.Near;

                    // Create a dimmed red brush.
                    XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));

                    // Draw the string.
                    gfx.DrawString(watermark, font, brush,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   format);
                }
                break;

                case 1:
                {
                    // Variation 2: Draw a watermark as an outlined graphical path.
                    // NYI: Does not work in Core build.

                    // Get an XGraphics object for drawing beneath the existing content.
                    var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

                    // Get the size (in points) of the text.
                    var size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page.
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a graphical path.
                    var path = new XGraphicsPath();

                    // Create a string format.
                    var format = new XStringFormat();
                    format.Alignment     = XStringAlignment.Near;
                    format.LineAlignment = XLineAlignment.Near;

                    // Add the text to the path.
                    // AddString is not implemented in PDFsharp Core.
                    path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   format);

                    // Create a dimmed red pen.
                    var pen = new XPen(XColor.FromArgb(128, 255, 0, 0), 2);

                    // Stroke the outline of the path.
                    gfx.DrawPath(pen, path);
                }
                break;

                case 2:
                {
                    // Variation 3: Draw a watermark as a transparent graphical path above text.
                    // NYI: Does not work in Core build.

                    // Get an XGraphics object for drawing above the existing content.
                    var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);

                    // Get the size (in points) of the text.
                    var size = gfx.MeasureString(watermark, font);

                    // Define a rotation transformation at the center of the page.
                    gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                    gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                    gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                    // Create a graphical path.
                    var path = new XGraphicsPath();

                    // Create a string format.
                    var format = new XStringFormat();
                    format.Alignment     = XStringAlignment.Near;
                    format.LineAlignment = XLineAlignment.Near;

                    // Add the text to the path.
                    // AddString is not implemented in PDFsharp Core.
                    path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
                                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                   format);

                    // Create a dimmed red pen and brush.
                    var    pen   = new XPen(XColor.FromArgb(50, 75, 0, 130), 3);
                    XBrush brush = new XSolidBrush(XColor.FromArgb(50, 106, 90, 205));

                    // Stroke the outline of the path.
                    gfx.DrawPath(pen, brush, path);
                }
                break;
                }
            }
            // Save the document...
            document.Save(filename);
        }
Exemple #21
0
 private static void DrawRectangle(XGraphics gfx,
     XColor backColor, XColor borderColor,
     XPen borderPen,
     int width, int height,
     int x, int y)
 {
     gfx.DrawRectangle(borderPen, x, y, width, height);
 }
Exemple #22
0
        void MapObject(SeriesCollection seriesCollection, DocumentObjectModel.Shapes.Charts.SeriesCollection domSeriesCollection)
        {
            foreach (DocumentObjectModel.Shapes.Charts.Series domSeries in domSeriesCollection)
            {
                Series series = seriesCollection.AddSeries();
                series.Name = domSeries.Name;

                if (domSeries.IsNull("ChartType"))
                {
                    DocumentObjectModel.Shapes.Charts.Chart chart = (DocumentObjectModel.Shapes.Charts.Chart)DocumentObjectModel.DocumentRelations.GetParentOfType(domSeries, typeof(DocumentObjectModel.Shapes.Charts.Chart));
                    series.ChartType = (ChartType)chart.Type;
                }
                else
                {
                    series.ChartType = (ChartType)domSeries.ChartType;
                }

                if (!domSeries.IsNull("DataLabel"))
                {
                    DataLabelMapper.Map(series.DataLabel, domSeries.DataLabel);
                }
                if (!domSeries.IsNull("LineFormat"))
                {
                    LineFormatMapper.Map(series.LineFormat, domSeries.LineFormat);
                }
                if (!domSeries.IsNull("FillFormat"))
                {
                    FillFormatMapper.Map(series.FillFormat, domSeries.FillFormat);
                }

                series.HasDataLabel = domSeries.HasDataLabel;
                if (domSeries.MarkerBackgroundColor.IsEmpty)
                {
                    series.MarkerBackgroundColor = XColor.Empty;
                }
                else
                {
#if noCMYK
                    series.MarkerBackgroundColor = XColor.FromArgb(domSeries.MarkerBackgroundColor.Argb);
#else
                    series.MarkerBackgroundColor =
                        ColorHelper.ToXColor(domSeries.MarkerBackgroundColor, domSeries.Document.UseCmykColor);
#endif
                }
                if (domSeries.MarkerForegroundColor.IsEmpty)
                {
                    series.MarkerForegroundColor = XColor.Empty;
                }
                else
                {
#if noCMYK
                    series.MarkerForegroundColor = XColor.FromArgb(domSeries.MarkerForegroundColor.Argb);
#else
                    series.MarkerForegroundColor =
                        ColorHelper.ToXColor(domSeries.MarkerForegroundColor, domSeries.Document.UseCmykColor);
#endif
                }
                series.MarkerSize = domSeries.MarkerSize.Point;
                if (!domSeries.IsNull("MarkerStyle"))
                {
                    series.MarkerStyle = (MarkerStyle)domSeries.MarkerStyle;
                }

                foreach (DocumentObjectModel.Shapes.Charts.Point domPoint in domSeries.Elements)
                {
                    if (domPoint != null)
                    {
                        Point point = series.Add(domPoint.Value);
                        FillFormatMapper.Map(point.FillFormat, domPoint.FillFormat);
                        LineFormatMapper.Map(point.LineFormat, domPoint.LineFormat);
                    }
                    else
                    {
                        series.Add(double.NaN);
                    }
                }
            }
        }
Exemple #23
0
    //public void Flush();
    //public void Flush(FlushIntention intention);

    #region Drawing

    // ----- Clear --------------------------------------------------------------------------------

    /// <summary>
    /// Fills the entire drawing surface with the specified color. The functions works only if
    /// the current transformation is identity, i.e. the function should be called only immediately
    /// after the XGraphics object was created.
    /// </summary>
    public void Clear(XColor color)
    {
      if (this.drawGraphics)
      {
#if GDI
        if (this.targetContext == XGraphicTargetContext.GDI)
          this.gfx.Clear(color.ToGdiColor());
#endif
#if WPF
        if (this.targetContext == XGraphicTargetContext.WPF)
        {
          Rect rc = new Rect();
          rc.Width = rc.Height = 10000;
          this.dc.DrawRectangle(new SolidColorBrush(color.ToWpfColor()), null, rc);
        }
#endif
      }

      if (this.renderer != null)
        this.renderer.Clear(color);
    }
Exemple #24
0
        /// <summary>
        /// Draws all charts inside the ChartFrame.
        /// </summary>
        public void Draw(XGraphics gfx)
        {
            // Draw frame of ChartFrame. First shadow frame.
            const int dx = 5;
            const int dy = 5;

            gfx.DrawRoundedRectangle(XBrushes.Gainsboro,
                                     _location.X + dx, _location.Y + dy,
                                     _size.Width, _size.Height, 20, 20);

            XRect chartRect            = new XRect(_location.X, _location.Y, _size.Width, _size.Height);
            XLinearGradientBrush brush = new XLinearGradientBrush(chartRect, XColor.FromArgb(0xFFD0DEEF), XColors.White,
                                                                  XLinearGradientMode.Vertical);
            XPen penBorder = new XPen(XColors.SteelBlue, 2.5);

            gfx.DrawRoundedRectangle(penBorder, brush,
                                     _location.X, _location.Y, _size.Width, _size.Height,
                                     15, 15);

            XGraphicsState state = gfx.Save();

            gfx.TranslateTransform(_location.X, _location.Y);

            // Calculate rectangle for all charts. Y-Position will be moved for each chart.
            int        charts          = _chartList.Count;
            const uint dxChart         = 20;
            const uint dyChart         = 20;
            const uint dyBetweenCharts = 30;
            XRect      rect            = new XRect(dxChart, dyChart,
                                                   _size.Width - 2 * dxChart,
                                                   (_size.Height - (charts - 1) * dyBetweenCharts - 2 * dyChart) / charts);

            // draw each chart in list
            foreach (Chart chart in _chartList)
            {
                RendererParameters parms = new RendererParameters(gfx, rect);
                parms.DrawingItem = chart;

                ChartRenderer renderer = GetChartRenderer(chart, parms);
                renderer.Init();
                renderer.Format();
                renderer.Draw();

                rect.Y += rect.Height + dyBetweenCharts;
            }
            gfx.Restore(state);

            //      // Calculate rectangle for all charts. Y-Position will be moved for each chart.
            //      int charts = chartList.Count;
            //      uint dxChart = 0;
            //      uint dyChart = 0;
            //      uint dyBetweenCharts = 0;
            //      XRect rect = new XRect(dxChart, dyChart,
            //        size.Width - 2 * dxChart,
            //        (size.Height - (charts - 1) * dyBetweenCharts - 2 * dyChart) / charts);
            //
            //      // draw each chart in list
            //      foreach (Chart chart in chartList)
            //      {
            //        RendererParameters parms = new RendererParameters(gfx, rect);
            //        parms.DrawingItem = chart;
            //
            //        ChartRenderer renderer = GetChartRenderer(chart, parms);
            //        renderer.Init();
            //        renderer.Format();
            //        renderer.Draw();
            //
            //        rect.Y += rect.Height + dyBetweenCharts;
            //      }
        }
Exemple #25
0
        /// <summary>
        /// Setups the shading from the specified brush.
        /// </summary>
        public void SetupFromBrush(XLinearGradientBrush brush)
        {
            if (brush == null)
            {
                throw new ArgumentNullException("brush");
            }

            PdfColorMode colorMode = this.document.Options.ColorMode;
            XColor       color1    = ColorSpaceHelper.EnsureColorMode(colorMode, brush.color1);
            XColor       color2    = ColorSpaceHelper.EnsureColorMode(colorMode, brush.color2);

            PdfDictionary function = new PdfDictionary();

            Elements[Keys.ShadingType] = new PdfInteger(2);
            if (colorMode != PdfColorMode.Cmyk)
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
            }
            else
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
            }

            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

            if (brush.useRect)
            {
                switch (brush.linearGradientMode)
                {
                case XLinearGradientMode.Horizontal:
                    x1 = brush.rect.x;
                    y1 = brush.rect.y;
                    x2 = brush.rect.x + brush.rect.width;
                    y2 = brush.rect.y;
                    break;

                case XLinearGradientMode.Vertical:
                    x1 = brush.rect.x;
                    y1 = brush.rect.y;
                    x2 = brush.rect.x;
                    y2 = brush.rect.y + brush.rect.height;
                    break;

                case XLinearGradientMode.ForwardDiagonal:
                    x1 = brush.rect.x;
                    y1 = brush.rect.y;
                    x2 = brush.rect.x + brush.rect.width;
                    y2 = brush.rect.y + brush.rect.height;
                    break;

                case XLinearGradientMode.BackwardDiagonal:
                    x1 = brush.rect.x + brush.rect.width;
                    y1 = brush.rect.y;
                    x2 = brush.rect.x;
                    y2 = brush.rect.y + brush.rect.height;
                    break;
                }
            }
            else
            {
                x1 = brush.point1.x;
                y1 = brush.point1.y;
                x2 = brush.point2.x;
                y2 = brush.point2.y;
            }
            Elements[Keys.Coords] = new PdfLiteral("[{0:0.###} {1:0.###} {2:0.###} {3:0.###}]", x1, y1, x2, y2);

            //Elements[Keys.Background] = new PdfRawItem("[0 1 1]");
            //Elements[Keys.Domain] =
            Elements[Keys.Function] = function;
            //Elements[Keys.Extend] = new PdfRawItem("[true true]");

            string clr1 = "[" + PdfEncoders.ToString(color1, colorMode) + "]";
            string clr2 = "[" + PdfEncoders.ToString(color2, colorMode) + "]";

            function.Elements["/FunctionType"] = new PdfInteger(2);
            function.Elements["/C0"]           = new PdfLiteral(clr1);
            function.Elements["/C1"]           = new PdfLiteral(clr2);
            function.Elements["/Domain"]       = new PdfLiteral("[0 1]");
            function.Elements["/N"]            = new PdfInteger(1);
        }
    /// <summary>
    ///
    /// </summary>
    private void PrintReport()
    {
        //if space is required, then it can be passed by - char
        //the - will remove by space

        string username    = "******";
        string titel       = "null";
        string showfilter  = "null";
        string curdate     = "null";
        string paperformat = string.Empty;
        string papersize   = string.Empty;
        string table       = string.Empty;
        string fields      = string.Empty;
        string whereclause = string.Empty;
        string groupby     = "NONE";
        string orderby     = string.Empty;
        string reporttype  = string.Empty;

        string securityKey = string.Empty;

        string selectSql          = string.Empty;
        string countSql           = string.Empty;
        string gbselectexpression = string.Empty;
        string reportCode         = string.Empty;

        EPageSize    EpageSize;
        EPaperFormat EpaperFormat;

        DBUtil.CONN_STRING = ConfigurationManager.ConnectionStrings["obcore_connectionstring"].ConnectionString;
        try
        {
            string   QueryStringUrl = Server.UrlDecode(Request.Url.Query.Substring(Request.Url.Query.IndexOf('?') + 1));
            string[] KeyValues      = QueryStringUrl.Split('&');

            for (int i = 0; i < KeyValues.Length; i++)
            {
                string[] KeyValuePair = KeyValues[i].Split('=');
                string   key          = KeyValuePair.Length > 0 ? KeyValuePair[0].Trim() : string.Empty;
                string   value        = KeyValues[i].Substring(KeyValues[i].IndexOf('=') + 1).Trim();

                switch (key)
                {
                case "username":
                    username = value;
                    break;

                case "securityKey":
                    securityKey = value;
                    break;

                case "titel":
                    titel = value;
                    break;

                case "showfilter":
                    showfilter = value;
                    break;

                case "curdate":
                    curdate = value;
                    break;

                case "paperformat":
                    paperformat = value;
                    break;

                case "papersize":
                    papersize = value;
                    break;

                case "reporttype":
                    reporttype = value;
                    break;

                case "reportcode":
                    reportCode = value;
                    break;

                case "table":
                    table = value.Replace("@@@", "\"");
                    break;

                case "fields":
                    fields = value;
                    break;

                case "whereclause":
                    whereclause = value;
                    break;

                case "groupby":
                    groupby = value;
                    break;

                case "orderby":
                    orderby = value;
                    break;

                case "gbselectexpression":
                    gbselectexpression = value;
                    break;
                }
            }


            if (!string.IsNullOrEmpty(fields) && !string.IsNullOrEmpty(table))
            {
                selectSql = " select " + fields + " from " + table;

                if (!string.IsNullOrEmpty(whereclause))
                {
                    selectSql += " where " + whereclause + " ";
                }

                if (!groupby.Equals("NONE") && !string.IsNullOrEmpty(groupby))
                {
                    if (reporttype == "Regular")
                    {
                        countSql = " select count(*)," + groupby + " from " + table;
                    }
                    else
                    {
                        countSql = " select " + gbselectexpression + "," + groupby + " from " + table;
                    }

                    if (!string.IsNullOrEmpty(whereclause))
                    {
                        countSql += " where " + whereclause + " ";
                    }

                    countSql += " group by " + groupby;

                    selectSql += " order by " + groupby;
                }

                if (!string.IsNullOrEmpty(orderby))
                {
                    selectSql += selectSql.Contains("order by") == true ? " , " + orderby : " order by " + orderby;
                    if (countSql != string.Empty)
                    {
                        countSql += " order by " + orderby;
                    }
                }
            }

            Dictionary <string, string> dicParams = new Dictionary <string, string>();

            username = username != "null" && securityKey != string.Empty ? "Static Name" : "null";

            dicParams.Add("username", username);
            dicParams.Add("titel", titel);

            showfilter = showfilter != "null" ? whereclause == string.Empty ? "De data wordt niet gefiltered"
                : whereclause
                : showfilter;
            dicParams.Add("showfilter", showfilter);
            dicParams.Add("curdate", curdate.Equals("null") == true ? "null" : DateTime.Now.ToString("dd/MM/yyyy"));

            switch (papersize)
            {
            case "a3":
                EpageSize = EPageSize.A3;
                break;

            case "a4":
                EpageSize = EPageSize.A4;
                break;

            default:
                EpageSize = EPageSize.A4;
                break;
            }

            switch (paperformat)
            {
            case "landscape":
                EpaperFormat = EPaperFormat.LandScape;
                break;

            case "portrait":
                EpaperFormat = EPaperFormat.Portrait;
                break;

            default:
                EpaperFormat = EPaperFormat.Portrait;
                break;
            }

            ReportUtil oReportUtil = new ReportUtil();

            ReportProperties data = oReportUtil.GetReportProperties(selectSql, reportCode, dicParams, EpageSize, EpaperFormat, Server.MapPath(FileNameManager.PdfFileName));

            DataTable recordCountTableForEachGroup = oReportUtil.GetRecordCountForEachGroup(countSql, reportCode);

            switch (reporttype)
            {
            case "Regular":
                oReportUtil.GenerateRegularReport(data, recordCountTableForEachGroup, Response);
                break;

            case "Piechart":
            case "Histogram":
                Dictionary <string, string> groupColors =
                    new ColorUtil().GetGroupColors(reportCode, recordCountTableForEachGroup, table, groupby);
                List <Group> oListGroup = new List <Group>();
                for (int i = 0; i < recordCountTableForEachGroup.Rows.Count; i++)
                {
                    Group oGroup = new Group();
                    oGroup.GroupValue  = double.Parse(recordCountTableForEachGroup.Rows[i][0].ToString());
                    oGroup.GroupName   = recordCountTableForEachGroup.Rows[i][groupby].ToString();
                    oGroup.GroupColour = XColor.FromArgb(System.Drawing.ColorTranslator.FromHtml("#" + groupColors[oGroup.GroupName]));
                    oListGroup.Add(oGroup);
                }

                if (reporttype == "Piechart")
                {
                    oReportUtil.GeneratePieChart(data, Response, oListGroup);
                }
                else if (reporttype == "Histogram")
                {
                    oReportUtil.GenerateColumnChart(data, Response, oListGroup, groupby);
                }
                break;

            default:
                oReportUtil.GenerateRegularReport(data, recordCountTableForEachGroup, Response);
                break;
            }
        }
        catch (Exception oEx)
        {
            Response.Write("Following server error occurs...<br/>");
            Response.Write("Select sql:" + selectSql + "<br/>");
            Response.Write("Count sql:" + countSql + "<br/>");
            Response.Write(oEx.Message + "<br/>");
            Response.Write(oEx.StackTrace);
        }
    }
Exemple #27
0
        /// <summary>
        /// Adds the specified outline entry.
        /// </summary>
        /// <param name="title">The outline text.</param>
        /// <param name="destinationPage">The destination page.</param>
        /// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
        /// <param name="style">The font style used to draw the outline text.</param>
        /// <param name="textColor">The color used to draw the outline text.</param>
        public PdfOutline Add(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style, XColor textColor)
        {
            PdfOutline outline = new PdfOutline(title, destinationPage, opened, style, textColor);

            Add(outline);
            return(outline);
        }
Exemple #28
0
    public static bool PatchImage(IAssetDataForImage __instance, XTexture2D?source, XRectangle?sourceArea, XRectangle?targetArea, PatchMode patchMode)
    {
        if (!Config.SMAPI.ApplyPatchEnabled)
        {
            return(true);
        }

        // get texture
        if (source is null)
        {
            return(ThrowSourceTextureNullException <bool>(nameof(source)));
        }

        XTexture2D target = __instance.Data;

        // get areas
        sourceArea ??= new(0, 0, source.Width, source.Height);
        targetArea ??= new(0, 0, Math.Min(sourceArea.Value.Width, target.Width), Math.Min(sourceArea.Value.Height, target.Height));

        // validate
        if (!source.Bounds.Contains(sourceArea.Value))
        {
            return(ThrowArgumentOutOfRangeException <bool>(nameof(sourceArea), "The source area is outside the bounds of the source texture."));
        }
        if (!target.Bounds.Contains(targetArea.Value))
        {
            return(ThrowArgumentOutOfRangeException <bool>(nameof(targetArea), "The target area is outside the bounds of the target texture."));
        }
        if (sourceArea.Value.Size != targetArea.Value.Size)
        {
            return(ThrowNotSameSizeException <bool>());
        }

        if (GL.Texture2DExt.CopyTexture(source, sourceArea.Value, target, targetArea.Value, patchMode))
        {
            return(false);
        }

        // get source data
        int pixelCount = sourceArea.Value.Width * sourceArea.Value.Height;
        var sourceData = GC.AllocateUninitializedArray <XColor>(pixelCount);

        source.GetData(0, sourceArea, sourceData, 0, pixelCount);

        // merge data in overlay mode
        if (patchMode == PatchMode.Overlay)
        {
            // get target data
            var targetData = GC.AllocateUninitializedArray <XColor>(pixelCount);
            target.GetData(0, targetArea, targetData, 0, pixelCount);

            // merge pixels
            for (int i = 0; i < sourceData.Length; i++)
            {
                var above = sourceData[i];
                var below = targetData[i];

                // shortcut transparency
                if (above.A < MinOpacity)
                {
                    sourceData[i] = below;
                    continue;
                }
                if (below.A < MinOpacity)
                {
                    sourceData[i] = above;
                    continue;
                }

                // merge pixels
                // This performs a conventional alpha blend for the pixels, which are already
                // premultiplied by the content pipeline. The formula is derived from
                // https://shawnhargreaves.com/blog/premultiplied-alpha.html.
                float alphaBelow = 1 - (above.A / 255f);
                sourceData[i] = new XColor(
                    (int)(above.R + (below.R * alphaBelow)),               // r
                    (int)(above.G + (below.G * alphaBelow)),               // g
                    (int)(above.B + (below.B * alphaBelow)),               // b
                    Math.Max(above.A, below.A)                             // a
                    );
            }
        }

        // patch target texture
        target.SetData(0, targetArea, sourceData, 0, pixelCount);
        return(false);
    }
Exemple #29
0
        private static void AddMainPage(PdfDocument document, AssesmentReportTO report)
        {
            // Create an empty page
            PdfPage page = document.AddPage();

            // Get an XGraphics object for drawing
            XGraphics      gfx = XGraphics.FromPdfPage(page);
            XTextFormatter tf  = new XTextFormatter(gfx);

            tf.Alignment = XParagraphAlignment.Left;

            AddHeader(gfx, report, page);
            AddAbout(gfx, report);

            // -------------------Info Section
            int heightSpace      = 70;
            int leftMargin       = 20;
            int subtitleWidth    = 150;
            int sectionTextWidth = 180;
            int roleTitleWidth   = 90;
            int colorWidth       = 20;

            //XBrush backgroundBrush = new
            XPen backgroundPen = new XPen(XColor.FromArgb(0, 238, 238, 238), 1);

            gfx.DrawRectangle(XBrushes.DarkSlateGray, new XRect(10, heightSpace + 35, page.Width - 10 * 2, 105));

            XBrush resumeBrush = XBrushes.White;

            // Person Name
            heightSpace = heightSpace + 50;
            gfx.DrawString("Persona evaluada:", subtitleFont, resumeBrush,
                           new XRect(leftMargin, heightSpace, subtitleWidth, 20),
                           XStringFormats.TopLeft);
            gfx.DrawString(report.AssesmentInfo.Employee.Name, regularFont, resumeBrush,
                           new XRect(leftMargin + subtitleWidth, heightSpace, 300, 20),
                           XStringFormats.TopLeft);

            if (report.Analysis != null && report.Analysis.RoleResult != null)
            {
                // Title Obtained
                heightSpace = heightSpace + 30;
                gfx.DrawString("Resultado:", subtitleFont, resumeBrush,
                               new XRect(leftMargin, heightSpace, roleTitleWidth, 20),
                               XStringFormats.TopLeft);
                gfx.DrawString(report.Analysis.RoleResult.Title.ToUpper(), regularFont, resumeBrush,
                               new XRect(leftMargin + subtitleWidth, heightSpace, 300, 20),
                               XStringFormats.TopLeft);

                // Points Obtained
                heightSpace = heightSpace + 30;
                gfx.DrawString("Puntos:", subtitleFont, resumeBrush,
                               new XRect(leftMargin, heightSpace, roleTitleWidth, 20),
                               XStringFormats.TopLeft);
                gfx.DrawString(report.Analysis.RoleResult.Points.ToString() + " / " + report.Analysis.RoleResult.PossiblePoints.ToString(), regularFont, resumeBrush,
                               new XRect(leftMargin + subtitleWidth, heightSpace, 300, 20),
                               XStringFormats.TopLeft);
            }

            // Sections Results
            heightSpace = heightSpace + 60;
            gfx.DrawString("DETALLE DE LA EVALUACIÓN", subtitleFont, XBrushes.Black,
                           new XRect(leftMargin, heightSpace, subtitleWidth, 20),
                           XStringFormats.TopLeft);

            heightSpace = heightSpace + 5;
            AddTitleLine(gfx, page, heightSpace);

            if (report.Analysis != null)
            {
                if (report.Analysis.RoleLevels != null)
                {
                    heightSpace = heightSpace + 30;
                    foreach (var item in report.Analysis.RoleLevels)
                    {
                        int paragraphHeight = 20;
                        if (item.Description.Length > 50)
                        {
                            paragraphHeight = item.Description.Length / 50 * 30;
                            if (paragraphHeight < 40)
                            {
                                paragraphHeight = 40;
                            }
                        }

                        XFont roleFont = regularFont;
                        if (report.Analysis.RoleResult.Title.ToLower().Contains(item.Name.ToLower()))
                        {
                            roleFont = regularBoldFont;
                        }

                        //Name
                        tf.DrawString(item.Name, roleFont, XBrushes.Black,
                                      new XRect(leftMargin + colorWidth, heightSpace, roleTitleWidth + 10, paragraphHeight),
                                      XStringFormats.TopLeft);

                        //Description
                        tf.DrawString(item.Description, roleFont, XBrushes.Black,
                                      new XRect(leftMargin + roleTitleWidth + colorWidth + 10, heightSpace, 400, paragraphHeight),
                                      XStringFormats.TopLeft);

                        heightSpace = heightSpace + paragraphHeight + 10;
                    }
                }
            }

            // Sections Results
            heightSpace = heightSpace + 20;
            gfx.DrawString("DETALLE DE LAS CAPACIDADES", subtitleFont, XBrushes.Black,
                           new XRect(leftMargin, heightSpace, subtitleWidth, 20),
                           XStringFormats.TopLeft);

            heightSpace = heightSpace + 5;
            AddTitleLine(gfx, page, heightSpace);

            heightSpace = heightSpace + 30;
            int barSize = 250;

            foreach (var item in report.Sections)
            {
                int itemBarSize = Convert.ToInt32(barSize * item.Percentage / 100);

                //Name
                tf.DrawString(item.Name, regularFont, XBrushes.Black,
                              new XRect(leftMargin, heightSpace, sectionTextWidth, 35),
                              XStringFormats.TopLeft);

                XBrush resultBrush = GetBrushByPercentage(item.Percentage);

                //Bar
                gfx.DrawRectangle(resultBrush, new XRect(leftMargin + sectionTextWidth + 20, heightSpace + 10, itemBarSize, 2));

                //Percentage
                tf.DrawString(item.Percentage.ToString() + "%", regularFont, resultBrush,
                              new XRect(leftMargin + sectionTextWidth + barSize + 30, heightSpace, 50, 35),
                              XStringFormats.TopLeft);

                heightSpace = heightSpace + 30;
            }
        }
Exemple #30
0
        private void createDocument()
        {
            PdfDocument   document    = new PdfDocument();
            PdfPage       page        = document.AddPage();
            double        pointsPermm = page.Height / page.Height.Millimeter;
            XGraphics     gfx         = XGraphics.FromPdfPage(page);
            XFont         Times11     = new XFont("Times New Roman", 11);
            XFont         Times11Bold = new XFont("Times New Roman", 11, XFontStyle.Bold);
            XFont         Times9      = new XFont("Times New Roman", 9);
            XStringFormat left        = new XStringFormat();

            left.Alignment = XStringAlignment.Near;
            XStringFormat right = new XStringFormat();

            right.Alignment = XStringAlignment.Far;
            XStringFormat center = new XStringFormat();

            center.Alignment = XStringAlignment.Center;

            byte[] data;
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("FolkBok.Images.FolkLogo.png"))
            {
                int count = (int)stream.Length;
                data = new byte[count];
                stream.Read(data, 0, count);
            }
            MemoryStream mstream = new MemoryStream(data);
            BitmapImage  image   = new BitmapImage();

            image.BeginInit();
            image.StreamSource = mstream;
            image.EndInit();
            double topLeftX = 14.5 * pointsPermm;
            double topLeftY = 20.5 * pointsPermm;
            double height   = 29.55 * pointsPermm;
            double width    = 71.67 * pointsPermm;

            gfx.DrawImage(XImage.FromBitmapSource(image), topLeftX, topLeftY, width, height);

            width = 181.74 * pointsPermm;
            gfx.DrawString("Faktura", new XFont("Times New Roman", 24), XBrushes.Black, topLeftX + width, 27.63 * pointsPermm, right);

            topLeftY = 54.84 * pointsPermm - 1;
            height   = 5.67 * pointsPermm + 1;
            width    = 88.16 * pointsPermm;
            gfx.DrawRectangle(XBrushes.Black, topLeftX, topLeftY, width, height);
            System.Windows.Point lp = new System.Windows.Point(16.5 * pointsPermm, topLeftY);
            System.Windows.Point rp = new System.Windows.Point(16.5 * pointsPermm + width / 2, topLeftY);
            gfx.DrawString("Belopp", new XFont("Times New Roman", 14, XFontStyle.Bold), XBrushes.White, lp, left);
            gfx.DrawString(getAmountString(invoice.Sum), new XFont("Times New Roman", 14, XFontStyle.Bold), XBrushes.White, rp, left);

            topLeftY += height;
            height    = 31.25 * pointsPermm;
            gfx.DrawRectangle(XBrushes.Gainsboro, topLeftX, topLeftY, width, height);
            lp.Y = topLeftY;
            rp.Y = topLeftY;
            gfx.DrawString("Fakturanummer", Times11, XBrushes.Black, lp, left);
            gfx.DrawString(invoice.Number.ToString(), Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + height / 7;
            rp.Y = topLeftY + height / 7;
            gfx.DrawString("Fakturadatum", Times11, XBrushes.Black, lp, left);
            gfx.DrawString(invoice.Date.ToShortDateString(), Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + 2 * height / 7;
            rp.Y = topLeftY + 2 * height / 7;
            gfx.DrawString("Betalningsvillkor", Times11, XBrushes.Black, lp, left);
            gfx.DrawString("30 dagar", Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + 3 * height / 7;
            rp.Y = topLeftY + 3 * height / 7;
            gfx.DrawString("Förfallodag", Times11, XBrushes.Black, lp, left);
            gfx.DrawString(invoice.Date.AddDays(30).ToShortDateString(), Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + 4 * height / 7;
            rp.Y = topLeftY + 4 * height / 7;
            gfx.DrawString("Dröjsmålsränta", Times11, XBrushes.Black, lp, left);
            gfx.DrawString("8%", Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + 5 * height / 7;
            rp.Y = topLeftY + 5 * height / 7;
            gfx.DrawString("Er referens", Times11, XBrushes.Black, lp, left);
            gfx.DrawString(invoice.YourReference, Times11, XBrushes.Black, rp, left);
            lp.Y = topLeftY + 6 * height / 7;
            rp.Y = topLeftY + 6 * height / 7;
            gfx.DrawString("Vår referens", Times11, XBrushes.Black, lp, left);
            gfx.DrawString(invoice.OurReference, Times11, XBrushes.Black, rp, left);

            topLeftY = 114.34 * pointsPermm;
            width    = 181.74 * pointsPermm;
            height   = 4.49 * pointsPermm + 1;
            gfx.DrawRectangle(XBrushes.Black, topLeftX, topLeftY, width, height);
            gfx.DrawString("Beskrivning", Times11, XBrushes.White, new System.Windows.Point(topLeftX + pointsPermm, topLeftY), left);
            gfx.DrawString("Datum", Times11, XBrushes.White, new System.Windows.Point(topLeftX + 5 * width / 8, topLeftY), left);
            gfx.DrawString("Belopp", Times11, XBrushes.White, new System.Windows.Point(topLeftX + 13 * width / 16, topLeftY), left);

            topLeftY += height;
            foreach (InvoiceLine line in invoice.Lines)
            {
                gfx.DrawString(line.Description, Times11, XBrushes.Black, new System.Windows.Point(topLeftX + pointsPermm, topLeftY), left);
                gfx.DrawString(line.Date.ToShortDateString(), Times11, XBrushes.Black, new System.Windows.Point(topLeftX + 5 * width / 8, topLeftY), left);
                gfx.DrawString(line.Amount.ToString() + " kr", Times11, XBrushes.Black, new System.Windows.Point(topLeftX + width, topLeftY), right);
                topLeftY = topLeftY + 5 * pointsPermm;
            }

            gfx.DrawLine(XPens.Black, topLeftX + 5 * width / 8, topLeftY + pointsPermm, topLeftX + width, topLeftY + pointsPermm);
            topLeftY = topLeftY + 1 * pointsPermm;
            gfx.DrawString("Summa att betala", Times11Bold, XBrushes.Black, new System.Windows.Point(topLeftX + 13 * width / 16, topLeftY), right);
            gfx.DrawString(getAmountString(invoice.Sum), Times11Bold, XBrushes.Black, new System.Windows.Point(topLeftX + width, topLeftY), right);

            height = 5;
            System.Windows.Point p1 = new System.Windows.Point(lp.X, 153.56 * pointsPermm);
            System.Windows.Point p2 = new System.Windows.Point(p1.X + 23.55 * pointsPermm, 153.56 * pointsPermm);
            System.Windows.Point p3 = new System.Windows.Point(p2.X + 75.58 * pointsPermm, 153.56 * pointsPermm);
            System.Windows.Point p4 = new System.Windows.Point(p3.X + 20.78 * pointsPermm, 153.56 * pointsPermm);
            gfx.DrawString("Organisation", Times9, XBrushes.Black, p1, left);
            gfx.DrawString("Folktetten", Times9, XBrushes.Black, p2, left);
            gfx.DrawString("Tel.", Times9, XBrushes.Black, p3, left);
            gfx.DrawString("0706-141866", Times9, XBrushes.Black, p4, left);
            p1.Y += height * pointsPermm;
            p2.Y += height * pointsPermm;
            p3.Y += height * pointsPermm;
            p4.Y += height * pointsPermm;
            gfx.DrawString("Adress", Times9, XBrushes.Black, p1, left);
            gfx.DrawString("Skarpskyttevägen 22G Lgh 1201 226 42 Lund", Times9, XBrushes.Black, p2, left);
            gfx.DrawString("E-post", Times9, XBrushes.Black, p3, left);
            gfx.DrawString("*****@*****.**", Times9, XBrushes.Black, p4, left);
            p1.Y += height * pointsPermm;
            p2.Y += height * pointsPermm;
            p3.Y += height * pointsPermm;
            p4.Y += height * pointsPermm;
            gfx.DrawString("Org. Nr.", Times9, XBrushes.Black, p1, left);
            gfx.DrawString("802495-4656", Times9, XBrushes.Black, p2, left);
            gfx.DrawString("Hemsida", Times9, XBrushes.Black, p3, left);
            gfx.DrawString("www.folktetten.se", Times9, XBrushes.Black, p4, left);
            p2.Y += height * pointsPermm;
            gfx.DrawString("Godkänd för F-skatt", Times9, XBrushes.Black, p2, left);

            p2.X += 43.57 * pointsPermm;
            p2.Y  = 172 * pointsPermm;
            gfx.DrawString("INBETALNING/GIRERING AVI Nr 1", Times11, XBrushes.Black, p2, left);
            topLeftY = 176.55 * pointsPermm;
            topLeftX = 13 * pointsPermm;
            width    = 186.27 * pointsPermm;
            height   = 72.7 * pointsPermm;
            gfx.DrawLine(XPens.Black, topLeftX, topLeftY, topLeftX + width, topLeftY);
            gfx.DrawLine(XPens.Black, topLeftX, topLeftY + height, topLeftX + width, topLeftY + height);
            gfx.DrawLine(XPens.Black, topLeftX, topLeftY, topLeftX, topLeftY + height);
            gfx.DrawLine(XPens.Black, topLeftX + width, topLeftY, topLeftX + width, topLeftY + height);
            gfx.DrawLine(XPens.Black, topLeftX, topLeftY + height / 2, topLeftX + width, topLeftY + height / 2);
            gfx.DrawLine(XPens.Black, topLeftX + width / 2, topLeftY + height / 2, topLeftX + width / 2, topLeftY + height);

            p1.Y = 221.47 * pointsPermm;
            p1.X = 111.81 * pointsPermm;
            gfx.DrawString("Folktetten", Times11Bold, XBrushes.Black, p1, left);
            p1.Y += 4 * pointsPermm;
            gfx.DrawString("Philip Jönsson", Times11, XBrushes.Black, p1, left);
            p1.Y += 4 * pointsPermm;
            gfx.DrawString("Skarpskyttevägen 22G Lgh 1201", Times11, XBrushes.Black, p1, left);
            p1.Y += 4 * pointsPermm;
            gfx.DrawString("226 42 Lund", Times11, XBrushes.Black, p1, left);

            System.Windows.Point top    = new System.Windows.Point(120.76 * pointsPermm, 60.51 * pointsPermm);
            System.Windows.Point bottom = new System.Windows.Point(20.44 * pointsPermm, 221.47 * pointsPermm);
            string[]             lines  = invoice.Address.Split('\n');
            XFont font = Times11Bold;

            foreach (string line in lines)
            {
                gfx.DrawString(line, font, XBrushes.Black, top, left);
                gfx.DrawString(line, font, XBrushes.Black, bottom, left);
                bottom.Y += 4 * pointsPermm;
                top.Y    += 4 * pointsPermm;
                if (font.Bold)
                {
                    font = Times11;
                }
            }

            XBrush brush = new XSolidBrush(XColor.FromArgb(208, 206, 206));

            topLeftX = 14.5 * pointsPermm;
            topLeftY = 257.92 * pointsPermm;
            width    = 181.74 * pointsPermm;
            height   = 14.44 * pointsPermm;
            gfx.DrawRectangle(brush, topLeftX, topLeftY, width, height);
            topLeftX += 35.15 * pointsPermm;
            topLeftY += height / 3;
            width     = 52 * pointsPermm;
            height   /= 3;
            gfx.DrawRectangle(XBrushes.White, topLeftX, topLeftY, width, height);
            p1.X = topLeftX + width / 2;
            p1.Y = topLeftY;
            gfx.DrawString(getAmountString(invoice.Sum), Times11Bold, XBrushes.Black, p1, center);
            topLeftX += width + 4.78 * pointsPermm;
            gfx.DrawRectangle(XBrushes.White, topLeftX, topLeftY, width, height);
            p1.X = topLeftX + width / 2;
            gfx.DrawString("666-4791", Times11Bold, XBrushes.Black, p1, center);

            string filename = name + ".pdf";

            document.Save(filename);
            Process.Start(filename);
        }
        private void GenerateWatermarkedPdf()
        {
            string inputPdfolderPath = inputPdfFolderTextBox.Text;
            string watermark         = watermarkTextBox.Text;
            string outputFolderPath  = inputPdfolderPath + "_watermarked";
            Color  color             = watermarkColorTextBox.BackColor;
            double opacity           = 0.5;

            string dateChosen = dateToAddToWatermarkTimePicker.Value.ToString("d");

            if (!Directory.Exists(inputPdfolderPath))
            {
                MessageBox.Show("The provided folder path doesn't exist!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(watermark))
            {
                MessageBox.Show("The watermark text is empty!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (addDatecheckBox.Checked)
            {
                watermark = dateChosen + " - " + watermark;
            }

            if (!string.IsNullOrEmpty(outputFolderTextBox.Text))
            {
                outputFolderPath = outputFolderTextBox.Text;
            }

            if (inputPdfolderPath.Equals(outputFolderPath))
            {
                MessageBox.Show("Input and output folder are identical!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int emSize = 72 * 15 / watermark.Length;

            if (!DirCopyPDF(inputPdfolderPath, outputFolderPath, true))
            {
                return;
            }

            if (int.TryParse(watermarkOpacityTextBox.Text, out int opacityPourcent))
            {
                opacity = opacityPourcent / (float)100;
            }
            else
            {
                opacity = watermarkOpacityTrackBar.Value / (float)100;
                watermarkOpacityTextBox.Text = watermarkOpacityTrackBar.Value.ToString();
            }

            XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);

            XColor brushColor = XColor.FromArgb(color.ToArgb());

            brushColor.A = opacity;
            XBrush brush = new XSolidBrush(brushColor);

            string[] pdfFilePaths = Directory.GetFiles(outputFolderPath, "*.pdf", SearchOption.AllDirectories);

            toolStripProgressBar.Value   = 0;
            toolStripProgressBar.Minimum = 0;
            toolStripProgressBar.Maximum = pdfFilePaths.Length;

            toolStripStatusLabel.Text = "Begin watermarking...";

            foreach (string pdfFilePath in pdfFilePaths)
            {
                try
                {
                    File.SetAttributes(pdfFilePath, File.GetAttributes(pdfFilePath) & ~FileAttributes.ReadOnly);

                    // Take in pdf from the form
                    PdfDocument document = PdfReader.Open(pdfFilePath);

                    toolStripStatusLabel.Text = "Processing " + Path.GetFileName(pdfFilePath) + "...";

                    foreach (PdfPage page in document.Pages)
                    {
                        // Get an XGraphics object for drawing beneath the existing content.
                        XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);

                        // Get the size (in points) of the text.
                        XSize size = gfx.MeasureString(watermark, font);

                        // Define a rotation transformation at the center of the page.
                        gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                        gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                        gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                        // Create a string format.
                        XStringFormat format = new XStringFormat()
                        {
                            Alignment     = XStringAlignment.Near,
                            LineAlignment = XLineAlignment.Near
                        };

                        // Draw the string.
                        gfx.DrawString(watermark, font, brush,
                                       new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                       format);
                        gfx.Dispose();
                    }
                    document.Save(pdfFilePath);
                    toolStripProgressBar.Value += 1;
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occured while creating watermark on documents: " + e.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            toolStripStatusLabel.Text = "Done.";
        }
Exemple #32
0
        private void DrawChart(XGraphics g, PdfPage page, ChartMeetingType mtgType)
        {
            if (UsableSummaryCount(mtgType) > MinChartSeries)
            {
                if (_itemFont == null)
                {
                    throw new InvalidOperationException(nameof(_itemFont));
                }

                var c = new Chart(ChartType.Column2D);
                c.Font.Name = "Verdana";

                var xSeries = c.XValues.AddXSeries();
                var ySeries = c.SeriesCollection.AddSeries();

                c.YAxis.MaximumScale       = LargestDeviationMins;
                c.YAxis.MinimumScale       = -LargestDeviationMins;
                c.YAxis.LineFormat.Visible = true;

                c.PlotArea.LineFormat.Visible = true;

                c.YAxis.MajorTick                       = 5;
                c.YAxis.Title.Caption                   = Resources.OVERTIME_MINS;
                c.YAxis.Title.Orientation               = 90;
                c.YAxis.Title.VerticalAlignment         = PdfSharpCore.Charting.VerticalAlignment.Center;
                c.YAxis.HasMajorGridlines               = true;
                c.YAxis.MajorGridlines.LineFormat.Color = XColor.FromGrayScale(50);
                c.YAxis.MajorTickMark                   = TickMarkType.Outside;

                c.XAxis.MajorTickMark = TickMarkType.None;

                switch (mtgType)
                {
                case ChartMeetingType.Midweek:
                    c.XAxis.Title.Caption = Resources.MIDWEEK_MTGS;
                    break;

                case ChartMeetingType.Weekend:
                    c.XAxis.Title.Caption = Resources.WEEKEND_MTGS;
                    break;

                case ChartMeetingType.Both:
                    c.XAxis.Title.Caption = Resources.MIDWEEK_AND_WEEKEND_MTGS;
                    break;

                default:
                    throw new NotSupportedException();
                }

                var currentMonth = default(DateTime);

                if (_historicalASummary != null)
                {
                    foreach (var summary in _historicalASummary.Summaries)
                    {
                        if (UseSummary(summary, mtgType))
                        {
                            if (summary.MeetingDate.Year != currentMonth.Year ||
                                summary.MeetingDate.Month != currentMonth.Month)
                            {
                                var monthName = summary.MeetingDate.ToString("MMM", CultureInfo.CurrentUICulture);
                                xSeries.Add(monthName);
                                currentMonth = summary.MeetingDate;
                            }
                            else
                            {
                                xSeries.AddBlank();
                            }

                            var p = ySeries.Add(LimitOvertime(summary.Overtime.TotalMinutes));
                            p.FillFormat.Color =
                                XColor.FromKnownColor(p.Value > 0 ? XKnownColor.Red : XKnownColor.Green);
                        }
                    }
                }

                var frame = new ChartFrame();

                var chartHeight = _itemFont.Height * 15;
                frame.Size     = new XSize(page.Width - (_leftMargin * 2), chartHeight);
                frame.Location = new XPoint(_leftMargin, _currentY);
                frame.Add(c);
                frame.DrawChart(g);

                _currentY += chartHeight + (_itemFont.Height * 2);
            }
        }
Exemple #33
0
 /// <summary>
 /// Creates an XColor structure from the specified alpha value and color.
 /// </summary>
 public static XColor FromArgb(int alpha, XColor color)
 {
   color.A = ((byte)alpha) / 255.0;
   return color;
 }
Exemple #34
0
 [DllImport(lib, EntryPoint = "XLookupColor")]//, CLSCompliant(false)]
 public extern static int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem, ref XColor exact_def_color, ref XColor screen_def_color);
Exemple #35
0
 /// <summary>
 /// Sets the color with the selected item.
 /// </summary>
 protected override void OnSelectedIndexChanged(EventArgs e)
 {
     int index = SelectedIndex;
     if (index > 0)
     {
         ColorItem item = (ColorItem)Items[index];
         _color = item.Color;
     }
     base.OnSelectedIndexChanged(e);
 }
Exemple #36
0
 [DllImport(lib, EntryPoint = "XAllocColor")]//, CLSCompliant(false)]
 public extern static int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def);
Exemple #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XSolidBrush"/> class.
 /// </summary>
 public XSolidBrush(XColor color)
     : this(color, false)
 { }
Exemple #38
0
 public int SetBackground(XColor background)
 {
     return XSetBackground (display.Handle, Handle, background.Pixel);
 }
Exemple #39
0
        private static void DrawBadgeElement(Badge badge, XGraphics gfx)
        {
            var color = ConverterManager.HexToColorConverter(badge.ForegroundColor);
            XColor borderColor = new XColor { R = color.R, G = color.G, B = color.B };
            color = ConverterManager.HexToColorConverter(badge.BackgroundColor);
            XColor backColor = new XColor { R = color.R, G = color.G, B = color.B };
            color = ConverterManager.HexToColorConverter(badge.FontColor);
            XColor fontColor = new XColor { R = color.R, G = color.G, B = color.B };
            XPen pen = new XPen(borderColor, double.Parse(badge.BorderWidth.ToString()));

            DrawRectangle(gfx, backColor, borderColor, pen, badge.Width, badge.Height, badge.PositionX1, badge.PositionY1);
            DrawText(gfx, badge.Value, badge.Font, badge.FontStyle, badge.FontSize, badge.FontColor, badge.Width, badge.Height, badge.PositionX1, badge.PositionY1);
        }
Exemple #40
0
 public int SetBackgroundColor(XColor color)
 {
     return XSetWindowBackground (display.Handle, Handle, color.Pixel);
 }
Exemple #41
0
 [DllImport(lib, EntryPoint = "XCreatePixmapCursor")]//, CLSCompliant(false)]
 public extern static IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot);
        private void watermarkPDFBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int emSize = 72 * 15 / WatermarkText.Length;

            if (!DirCopyPDF(InputPdfolderPath, OutputFolderPath, true))
            {
                return;
            }

            XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);

            XColor brushColor = XColor.FromArgb(WatermarkColor.ToArgb());

            brushColor.A = WatermarkOpacity;
            XBrush brush = new XSolidBrush(brushColor);

            string[] pdfFilePaths = Directory.GetFiles(OutputFolderPath, "*.pdf", SearchOption.AllDirectories);

            // set progress bar maximum value
            watermarkPDFBackgroundWorker.ReportProgress(0, pdfFilePaths.Length);

            int currentFileNumber = 0;

            foreach (string pdfFilePath in pdfFilePaths)
            {
                currentFileNumber += 1;
                try
                {
                    File.SetAttributes(pdfFilePath, File.GetAttributes(pdfFilePath) & ~FileAttributes.ReadOnly);

                    // Take in pdf from the form
                    PdfDocument document = PdfReader.Open(pdfFilePath);

                    toolStripStatusLabel.Text = "Processing " + Path.GetFileName(pdfFilePath) + "...";

                    foreach (PdfPage page in document.Pages)
                    {
                        // Get an XGraphics object for drawing beneath the existing content.
                        XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);

                        // Get the size (in points) of the text.
                        XSize size = gfx.MeasureString(WatermarkText, font);

                        // Define a rotation transformation at the center of the page.
                        gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                        gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                        gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                        // Create a string format.
                        XStringFormat format = new XStringFormat()
                        {
                            Alignment     = XStringAlignment.Near,
                            LineAlignment = XLineAlignment.Near
                        };

                        // Draw the string.
                        gfx.DrawString(WatermarkText, font, brush,
                                       new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                                       format);
                        gfx.Dispose();
                    }
                    document.Save(pdfFilePath);
                    watermarkPDFBackgroundWorker.ReportProgress(currentFileNumber);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured while creating watermark on documents: " + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }
Exemple #43
0
 public int SetForeground(XColor foreground)
 {
     return XSetForeground (display.Handle, Handle, foreground.Pixel);
 }
Exemple #44
0
        /// <summary>
        /// Setups the shading from the specified brush.
        /// </summary>
        internal void SetupFromBrush(XLinearGradientBrush brush, XGraphicsPdfRenderer renderer)
        {
            if (brush == null)
            {
                throw new ArgumentNullException("brush");
            }

            PdfColorMode colorMode = _document.Options.ColorMode;
            XColor       color1    = ColorSpaceHelper.EnsureColorMode(colorMode, brush._color1);
            XColor       color2    = ColorSpaceHelper.EnsureColorMode(colorMode, brush._color2);

            PdfDictionary function = new PdfDictionary();

            Elements[Keys.ShadingType] = new PdfInteger(2);
            if (colorMode != PdfColorMode.Cmyk)
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
            }
            else
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
            }

            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

            if (brush._useRect)
            {
                XPoint pt1 = renderer.WorldToView(brush._rect.TopLeft);
                XPoint pt2 = renderer.WorldToView(brush._rect.BottomRight);

                switch (brush._linearGradientMode)
                {
                case XLinearGradientMode.Horizontal:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt2.X;
                    y2 = pt1.Y;
                    break;

                case XLinearGradientMode.Vertical:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt1.X;
                    y2 = pt2.Y;
                    break;

                case XLinearGradientMode.ForwardDiagonal:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt2.X;
                    y2 = pt2.Y;
                    break;

                case XLinearGradientMode.BackwardDiagonal:
                    x1 = pt2.X;
                    y1 = pt1.Y;
                    x2 = pt1.X;
                    y2 = pt2.Y;
                    break;
                }
            }
            else
            {
                XPoint pt1 = renderer.WorldToView(brush._point1);
                XPoint pt2 = renderer.WorldToView(brush._point2);

                x1 = pt1.X;
                y1 = pt1.Y;
                x2 = pt2.X;
                y2 = pt2.Y;
            }

            const string format = Config.SignificantFigures3;

            Elements[Keys.Coords] = new PdfLiteral("[{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "}]", x1, y1, x2, y2);

            //Elements[Keys.Background] = new PdfRawItem("[0 1 1]");
            //Elements[Keys.Domain] =
            Elements[Keys.Function] = function;
            //Elements[Keys.Extend] = new PdfRawItem("[true true]");

            string clr1 = "[" + PdfEncoders.ToString(color1, colorMode) + "]";
            string clr2 = "[" + PdfEncoders.ToString(color2, colorMode) + "]";

            function.Elements["/FunctionType"] = new PdfInteger(2);
            function.Elements["/C0"]           = new PdfLiteral(clr1);
            function.Elements["/C1"]           = new PdfLiteral(clr2);
            function.Elements["/Domain"]       = new PdfLiteral("[0 1]");
            function.Elements["/N"]            = new PdfInteger(1);
        }
Exemple #45
0
 public int SetWindowBorder(XColor color)
 {
     return XSetWindowBorder (display.Handle, Handle, color.Pixel);
 }
Exemple #46
0
 /// <summary>
 /// Convert from core color to WinForms color.
 /// </summary>
 public static XColor Convert(RColor c)
 {
     return(XColor.FromArgb(c.A, c.R, c.G, c.B));
 }
Exemple #47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XPen"/> class.
 /// </summary>
 public XPen(XColor color)
   : this(color, 1, false)
 { }
Exemple #48
0
        private void parse_text(XmlNodeList nodes)
        {
            double x, y, width, height, font_size;
            string align, font_family, font_style, prefix, suffix;
            bool   include_other_notes;
            Color  color;

            foreach (XmlNode node in nodes)
            {
                if (node.Attributes.Count > 0)
                {
                    if (node.Attributes["include_other_notes"] != null)
                    {
                        include_other_notes = Convert.ToBoolean(node.Attributes["include_other_notes"].Value);
                    }
                    else
                    {
                        include_other_notes = false;
                    }
                    if (node.Attributes["x"] != null)
                    {
                        x = Convert.ToDouble(node.Attributes["x"].Value);
                    }
                    else
                    {
                        x = 0;
                    }
                    if (node.Attributes["y"] != null)
                    {
                        y = Convert.ToDouble(node.Attributes["y"].Value);
                    }
                    else
                    {
                        y = 0;
                    }
                    if (node.Attributes["width"] != null)
                    {
                        width = Convert.ToDouble(node.Attributes["width"].Value);
                    }
                    else
                    {
                        width = 0;
                    }
                    if (node.Attributes["height"] != null)
                    {
                        height = Convert.ToDouble(node.Attributes["height"].Value);
                    }
                    else
                    {
                        height = 0;
                    }
                    if (node.Attributes["size"] != null)
                    {
                        font_size = Convert.ToDouble(node.Attributes["size"].Value);
                    }
                    else
                    {
                        font_size = 14;
                    }
                    if (node.Attributes["prefix"] != null)
                    {
                        prefix = node.Attributes["prefix"].Value;
                    }
                    else
                    {
                        prefix = "";
                    }
                    if (node.Attributes["suffix"] != null)
                    {
                        suffix = node.Attributes["suffix"].Value;
                    }
                    else
                    {
                        suffix = "";
                    }
                    if (node.Attributes["font"] != null)
                    {
                        font_family = node.Attributes["font"].Value;
                    }
                    else
                    {
                        font_family = "Arial";
                    }
                    if (node.Attributes["style"] != null)
                    {
                        font_style = node.Attributes["style"].Value;
                    }
                    else
                    {
                        font_style = "regular";
                    }
                    if (node.Attributes["align"] != null)
                    {
                        align = node.Attributes["align"].Value;
                    }
                    else
                    {
                        align = "left";
                    }
                    if (node.Attributes["color"] != null)
                    {
                        try {
                            color = ColorTranslator.FromHtml(node.Attributes["color"].Value);
                        } catch {
                            color = Color.Black;
                        }
                    }
                    else
                    {
                        color = Color.Black;
                    }

                    XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.WinAnsi, PdfFontEmbedding.Default);

                    XFontStyle style = XFontStyle.Regular;
                    switch (font_style.ToLower())
                    {
                    case "bold":
                        style = XFontStyle.Bold;
                        break;

                    case "bolditalic":
                        style = XFontStyle.BoldItalic;
                        break;

                    case "italic":
                        style = XFontStyle.Italic;
                        break;

                    case "strikeout":
                        style = XFontStyle.Strikeout;
                        break;

                    case "underline":
                        style = XFontStyle.Underline;
                        break;
                    }

                    XFont         font   = new XFont(font_family, font_size, style, options);
                    XStringFormat format = new XStringFormat();
                    switch (align.ToLower())
                    {
                    case "left":
                        format.Alignment = XStringAlignment.Near;
                        break;

                    case "center":
                        format.Alignment = XStringAlignment.Center;
                        break;

                    case "right":
                        format.Alignment = XStringAlignment.Far;
                        break;
                    }

                    prefix = System.Text.RegularExpressions.Regex.Unescape(prefix);
                    suffix = System.Text.RegularExpressions.Regex.Unescape(suffix);

                    switch (node.Name.ToLower())
                    {
                    case "cong_name":
                        this.gfx.DrawString(prefix + Form1.settings.cong_name + suffix, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), format);
                        break;

                    case "map_name":
                        this.gfx.DrawString(prefix + Form1.map.name + suffix, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), format);
                        break;

                    case "dnc_list":
                        if (include_other_notes && Form1.map.notes.Length > 0)
                        {
                            suffix += "\n" + Form1.map.notes;
                        }
                        this.tf.DrawString(prefix + generate_dnc_list(font, width) + suffix, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), XStringFormats.TopLeft);
                        break;

                    case "other_notes":
                        this.tf.DrawString(prefix + Form1.map.notes + suffix, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), XStringFormats.TopLeft);
                        break;

                    case "directions":
                        this.tf.DrawString(prefix + generate_directions(font, width) + suffix, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), XStringFormats.TopLeft);
                        break;

                    case "text":
                        this.gfx.DrawString(node.InnerText, font, new XSolidBrush(XColor.FromArgb(color)), new XRect(x, y, width, height), format);
                        break;
                    }
                }
            }
        }
Exemple #49
0
		public XColor( XColor xc )
		{
			color = xc.color;
		}
Exemple #50
0
		internal extern static IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot);
        /// <summary>
        /// Renders the content of the page.
        /// </summary>
        public void Render(XGraphics gfx)
        {
            double x = 50, y = 100;
            var    fontH1     = new XFont("Times", 18, XFontStyle.Bold);
            var    font       = new XFont("Times", 12);
            var    fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);
            var    ls         = font.GetHeight();

            // Draw some text.
            gfx.DrawString("Create PDF on the fly with PDFsharp",
                           fontH1, XBrushes.Black, x, x);
            gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " +
                           "text and images on different targets.", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("The object used for drawing is the XGraphics object.",
                           font, XBrushes.Black, x, y);
            y += 2 * ls;

            // Draw an arc.
            var pen = new XPen(XColors.Red, 4);

            pen.DashStyle = XDashStyle.Dash;
            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

            // Draw a star.
            var gs = gfx.Save();

            gfx.TranslateTransform(x + 140, y + 30);
            for (var idx = 0; idx < 360; idx += 10)
            {
                gfx.RotateTransform(10);
                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }
            gfx.Restore(gs);

            // Draw a rounded rectangle.
            var rect = new XRect(x + 230, y, 100, 60);

            pen = new XPen(XColors.DarkBlue, 2.5);
            var color1 = XColor.FromKnownColor(KnownColor.DarkBlue);
            var color2 = XColors.Red;
            var lbrush = new XLinearGradientBrush(rect, color1, color2,
                                                  XLinearGradientMode.Vertical);

            gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10));

            // Draw a pie.
            pen           = new XPen(XColors.DarkOrange, 1.5);
            pen.DashStyle = XDashStyle.Dot;
            gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135);

            // Draw some more text.
            y += 60 + 2 * ls;
            gfx.DrawString("With XGraphics you can draw on a PDF page as well as " +
                           "on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y);
            y += ls * 1.1;
            gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y);
            x += 10;
            y += ls * 1.1;
            gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw above or beneath of the content of an existing PDF page",
                           font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y);
            x -= 10;
            y += ls * 1.1;
            gfx.DrawString("You can also import an existing PDF page and use it like " +
                           "an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y);
            y += ls * 1.1 * 2;
            gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a " +
                           "PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            gfx.DrawString("Below this text is a PDF form that will be visible when " +
                           "viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            var state   = gfx.Save();
            var rcImage = new XRect(100, y, 100, 100 * Math.Sqrt(2));

            gfx.DrawRectangle(XBrushes.Snow, rcImage);
            gfx.DrawImage(XPdfForm.FromFile("../../../../assets/PDFs/SomeLayout.pdf"), rcImage);
            gfx.Restore(state);
        }
Exemple #52
0
		internal extern static int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem, ref XColor exact_def_color, ref XColor screen_def_color);
Exemple #53
0
		internal extern static int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def);
Exemple #54
0
		internal static int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def)
		{
			DebugHelper.TraceWriteLine ("XAllocColor");
			return _XAllocColor(display, Colormap, ref colorcell_def);
		}
Exemple #55
0
		internal static IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot)
		{
			DebugHelper.TraceWriteLine ("XCreatePixmapCursor");
			return _XCreatePixmapCursor(display, source, mask, ref foreground_color, ref background_color, x_hot, y_hot);
		}
Exemple #56
0
		internal static int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem, ref XColor exact_def_color, ref XColor screen_def_color)
		{
			DebugHelper.TraceWriteLine ("XLookupColor");
			return _XLookupColor(display, Colormap, Coloranem, ref exact_def_color, ref screen_def_color);
		}
Exemple #57
0
		IntPtr GetReversibleControlGC (Control control, int line_width)
		{
			XGCValues	gc_values;
			IntPtr		gc;

			gc_values = new XGCValues();

			gc_values.subwindow_mode = GCSubwindowMode.IncludeInferiors;
			gc_values.line_width = line_width;
			gc_values.foreground = XBlackPixel(DisplayHandle, ScreenNo);

			// This logic will give us true rubber bands: (libsx, SANE_XOR)
			//mask = foreground ^ background; 
			//XSetForeground(DisplayHandle, gc, 0xffffffff);
			//XSetBackground(DisplayHandle, gc, background);
			//XSetFunction(DisplayHandle,   gc, GXxor);
			//XSetPlaneMask(DisplayHandle,  gc, mask);


			gc = XCreateGC(DisplayHandle, control.Handle, new IntPtr ((int) (GCFunction.GCSubwindowMode | GCFunction.GCLineWidth | GCFunction.GCForeground)), ref gc_values);
			uint foreground;
			uint background;

			XColor xcolor = new XColor();

			xcolor.red = (ushort)(control.ForeColor.R * 257);
			xcolor.green = (ushort)(control.ForeColor.G * 257);
			xcolor.blue = (ushort)(control.ForeColor.B * 257);
			XAllocColor(DisplayHandle, DefaultColormap, ref xcolor);
			foreground = (uint)xcolor.pixel.ToInt32();

			xcolor.red = (ushort)(control.BackColor.R * 257);
			xcolor.green = (ushort)(control.BackColor.G * 257);
			xcolor.blue = (ushort)(control.BackColor.B * 257);
			XAllocColor(DisplayHandle, DefaultColormap, ref xcolor);
			background = (uint)xcolor.pixel.ToInt32();

			uint mask = foreground ^ background; 

			XSetForeground(DisplayHandle, gc, (UIntPtr)0xffffffff);
			XSetBackground(DisplayHandle, gc, (UIntPtr)background);
			XSetFunction(DisplayHandle,   gc, GXFunction.GXxor);
			XSetPlaneMask(DisplayHandle,  gc, (IntPtr)mask);

			return gc;
		}
Exemple #58
0
		IntPtr GetReversibleScreenGC (Color backColor)
		{
			XGCValues	gc_values;
			IntPtr		gc;
			uint pixel;

			XColor xcolor = new XColor();
			xcolor.red = (ushort)(backColor.R * 257);
			xcolor.green = (ushort)(backColor.G * 257);
			xcolor.blue = (ushort)(backColor.B * 257);
			XAllocColor(DisplayHandle, DefaultColormap, ref xcolor);
			pixel = (uint)xcolor.pixel.ToInt32();


			gc_values = new XGCValues();

			gc_values.subwindow_mode = GCSubwindowMode.IncludeInferiors;
			gc_values.foreground = (IntPtr)pixel;

			gc = XCreateGC(DisplayHandle, RootWindow, new IntPtr ((int) (GCFunction.GCSubwindowMode | GCFunction.GCForeground)), ref gc_values);
			XSetForeground(DisplayHandle, gc, (UIntPtr)pixel);
			XSetFunction(DisplayHandle,   gc, GXFunction.GXxor);

			return gc;
		}
Exemple #59
0
		internal override IntPtr DefineCursor(Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot)
		{
			IntPtr	cursor;
			Bitmap	cursor_bitmap;
			Bitmap	cursor_mask;
			Byte[]	cursor_bits;
			Byte[]	mask_bits;
			Color	c_pixel;
			Color	m_pixel;
			int	width;
			int	height;
			IntPtr	cursor_pixmap;
			IntPtr	mask_pixmap;
			XColor	fg;
			XColor	bg;
			bool	and;
			bool	xor;

			if (XQueryBestCursor(DisplayHandle, RootWindow, bitmap.Width, bitmap.Height, out width, out height) == 0) {
				return IntPtr.Zero;
			}

			// Win32 only allows creation cursors of a certain size
			if ((bitmap.Width != width) || (bitmap.Width != height)) {
				cursor_bitmap = new Bitmap(bitmap, new Size(width, height));
				cursor_mask = new Bitmap(mask, new Size(width, height));
			} else {
				cursor_bitmap = bitmap;
				cursor_mask = mask;
			}

			width = cursor_bitmap.Width;
			height = cursor_bitmap.Height;

			cursor_bits = new Byte[(width / 8) * height];
			mask_bits = new Byte[(width / 8) * height];

			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					c_pixel = cursor_bitmap.GetPixel(x, y);
					m_pixel = cursor_mask.GetPixel(x, y);

					and = c_pixel == cursor_pixel;
					xor = m_pixel == mask_pixel;

					if (!and && !xor) {
						// Black
						// cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));	// The bit already is 0
						mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
					} else if (and && !xor) {
						// White
						cursor_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
						mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
#if notneeded
					} else if (and && !xor) {
						// Screen
					} else if (and && xor) {
						// Inverse Screen

						// X11 doesn't know the 'reverse screen' concept, so we'll treat them the same
						// we want both to be 0 so nothing to be done
						//cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));
						//mask_bits[y * width / 8 + x / 8] |= (byte)(01 << (x % 8));
#endif
					}
				}
			}

			cursor_pixmap = XCreatePixmapFromBitmapData(DisplayHandle, RootWindow, cursor_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
			mask_pixmap = XCreatePixmapFromBitmapData(DisplayHandle, RootWindow, mask_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
			fg = new XColor();
			bg = new XColor();

			fg.pixel = XWhitePixel(DisplayHandle, ScreenNo);
			fg.red = (ushort)65535;
			fg.green = (ushort)65535;
			fg.blue = (ushort)65535;

			bg.pixel = XBlackPixel(DisplayHandle, ScreenNo);

			cursor = XCreatePixmapCursor(DisplayHandle, cursor_pixmap, mask_pixmap, ref fg, ref bg, xHotSpot, yHotSpot);

			XFreePixmap(DisplayHandle, cursor_pixmap);
			XFreePixmap(DisplayHandle, mask_pixmap);

			return cursor;
		}
Exemple #60
-1
        public static void BeginBox(XGraphics gfx, int number, string title,
            double borderWidth, double borderHeight,
            XColor shadowColor, XColor backColor, XColor backColor2,
            XPen borderPen)
        {
            const int dEllipse = 15;
            XRect rect = new XRect(0, 20, 300, 200);
            if (number % 2 == 0)
                rect.X = 300 - 5;
            rect.Y = 40 + ((number - 1) / 2) * (200 - 5);
            rect.Inflate(-10, -10);
            XRect rect2 = rect;
            rect2.Offset(borderWidth, borderHeight);
            gfx.DrawRoundedRectangle(new XSolidBrush(shadowColor), rect2, new XSize(dEllipse + 8, dEllipse + 8));
            XLinearGradientBrush brush = new XLinearGradientBrush(rect, backColor, backColor2, XLinearGradientMode.Vertical);
            gfx.DrawRoundedRectangle(borderPen, brush, rect, new XSize(dEllipse, dEllipse));
            rect.Inflate(-5, -5);

            XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
            gfx.DrawString(title, font, XBrushes.Navy, rect, XStringFormats.TopCenter);

            rect.Inflate(-10, -5);
            rect.Y += 20;
            rect.Height -= 20;

            state = gfx.Save();
            gfx.TranslateTransform(rect.X, rect.Y);
        }