Beispiel #1
0
        /// <summary>
        /// Renders the OMR code.
        /// </summary>
        protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
        {
            XGraphicsState state = gfx.Save();

            switch (Direction)
            {
                case CodeDirection.RightToLeft:
                    gfx.RotateAtTransform(180, position);
                    break;

                case CodeDirection.TopToBottom:
                    gfx.RotateAtTransform(90, position);
                    break;

                case CodeDirection.BottomToTop:
                    gfx.RotateAtTransform(-90, position);
                    break;
            }

            //XPoint pt = center - size / 2;
            XPoint pt = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);
            uint value;
            uint.TryParse(Text, out value);
#if true
            // HACK: Project Wallenwein: set LK
            value |= 1;
            _synchronizeCode = true;
#endif
            if (_synchronizeCode)
            {
                XRect rect = new XRect(pt.X, pt.Y, _makerThickness, Size.Height);
                gfx.DrawRectangle(brush, rect);
                pt.X += 2 * _makerDistance;
            }
            for (int idx = 0; idx < 32; idx++)
            {
                if ((value & 1) == 1)
                {
                    XRect rect = new XRect(pt.X + idx * _makerDistance, pt.Y, _makerThickness, Size.Height);
                    gfx.DrawRectangle(brush, rect);
                }
                value = value >> 1;
            }
            gfx.Restore(state);
        }
Beispiel #2
0
        /// <summary>
        /// Align content vertically
        /// </summary>
        private void AlignVertically()
        {
            ArrayList objectList = new ArrayList(mOwnRowObjects);

            mOwnRowObjects.Clear();

            for (int i = 0; i < objectList.Count; i++)
            {
                RowObject oldObj = (RowObject)objectList[i];
                double    bottom = Math.Round(RowBottom.PosY - CellPadding, 6);

                XRect bbox = new XRect();
                bbox.String = mDoc.GetInfo(oldObj.id, "rect");
                bbox.Inset(-CellPadding, -CellPadding);


                if (bbox.Bottom > bottom && oldObj.pageNr == RowBottom.PageNr)
                {
                    double alpha = VerticalAlignment;
                    if (VerticalAlignment > 1)
                    {
                        alpha = 1;
                    }
                    double offset = alpha * (bbox.Bottom - bottom);
                    double width  = 0;
                    if (oldObj.obj is XImage)
                    {
                        width = Double.Parse(mDoc.GetInfo(oldObj.id, "Width"), new CultureInfo("en-US"));
                    }
                    mDoc.Delete(oldObj.id);
                    XRect newRect = new XRect();
                    newRect.String = bbox.String;
                    newRect.Move(0, -offset);
                    if (newRect.Bottom > bottom)
                    {
                        newRect.Bottom = bottom;
                    }

                    mDoc.Rect.String = newRect.String;

                    string theTextStyle = mDoc.TextStyle.String;

                    mDoc.TextStyle.String = oldObj.textStyle;
                    int iFont = mDoc.Font;
                    mDoc.Font = oldObj.font;

                    if (oldObj.obj is string)
                    {
                        AddHtml((string)(oldObj.obj));
                    }
                    else
                    if (oldObj.obj is XImage)
                    {
                        XImage image = (XImage)(oldObj.obj);
                        if (width == image.Width)
                        {
                            AddImage(image, false);
                        }
                        else
                        {
                            AddImage(image, true);
                        }
                    }

                    mDoc.Font             = iFont;
                    mDoc.TextStyle.String = theTextStyle;
                }
                else
                {
                    mOwnRowObjects.Add(oldObj);
                }
            }
        }
Beispiel #3
0
        // This sample shows three variations how to add a watermark text to an
        // existing PDF file.
        protected override void DoWork()
        {
            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("AltData/PDFsharp/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
            Diagnostics.ProcessHelper.Start(filename);
        }
 /// <summary>
 /// Draws a line specified by rect.
 /// </summary>
 public void DrawRectangle(XRect rect)
 {
     if (_pen != null)
         _gfx.DrawRectangle(_pen, rect);
 }
Beispiel #5
0
        /// <summary>
        /// Draws the text.
        /// </summary>
        /// <param name="text">The text to be drawn.</param>
        /// <param name="font">The font.</param>
        /// <param name="brush">The text brush.</param>
        /// <param name="layoutRectangle">The layout rectangle.</param>
        /// <param name="format">The format. Must be <c>XStringFormat.TopLeft</c></param>
        public void DrawString(string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format)
        {
            if (text == null)
                throw new ArgumentNullException("text");
            if (font == null)
                throw new ArgumentNullException("font");
            if (brush == null)
                throw new ArgumentNullException("brush");
            if (format.Alignment != XStringAlignment.Near || format.LineAlignment != XLineAlignment.Near)
                throw new ArgumentException("Only TopLeft alignment is currently implemented.");

            Text = text;
            Font = font;
            LayoutRectangle = layoutRectangle;

            if (text.Length == 0)
                return;

            CreateBlocks();

            CreateLayout();

            double dx = layoutRectangle.Location.X;
            double dy = layoutRectangle.Location.Y + _cyAscent;
            int count = _blocks.Count;
            for (int idx = 0; idx < count; idx++)
            {
                Block block = _blocks[idx];
                if (block.Stop)
                    break;
                if (block.Type == BlockType.LineBreak)
                    continue;
                _gfx.DrawString(block.Text, font, brush, dx + block.Location.X, dy + block.Location.Y);
            }
        }
    public void BeginContainer(XGraphicsContainer container, XRect dstrect, XRect srcrect, XGraphicsUnit unit)
    {
      // Before saving, the current transformation matrix must be completely realized.
      BeginGraphic();
      RealizeTransform();
      this.gfxState.InternalState = container.InternalState;
      SaveState();
      //throw new NotImplementedException("BeginContainer");
      //      PdfGraphicsState pdfstate = (PdfGraphicsState)this.gfxState.Clone();
      //      this.gfxStateStack.Push(pdfstate);
      //      container.Handle = pdfstate;
      //      container.Handle = this.gfxState.Clone();

      //      Matrix matrix = new Matrix();
      //      matrix.Translate(srcrect.X, srcrect.Y);
      //      matrix.Scale(dstrect.Width / srcrect.Width, dstrect.Height / srcrect.Height);
      //      matrix.Translate(dstrect.X, dstrect.Y);
      //      Transform = matrix;
    }
    // ----- DrawRectangles -----------------------------------------------------------------------

    public void DrawRectangles(XPen pen, XBrush brush, XRect[] rects)
    {
      int count = rects.Length;
      for (int idx = 0; idx < count; idx++)
      {
        XRect rect = rects[idx];
        DrawRectangle(pen, brush, rect.X, rect.Y, rect.Width, rect.Height);
      }
    }
        // ----- DrawString ---------------------------------------------------------------------------

        public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format)
        {
            double x = rect.X;
            double y = rect.Y;

            double lineSpace = font.GetHeight();
            double cyAscent = lineSpace * font.CellAscent / font.CellSpace;
            double cyDescent = lineSpace * font.CellDescent / font.CellSpace;
            double width = _gfx.MeasureString(s, font).Width;

            //bool bold = (font.Style & XFontStyle.Bold) != 0;
            //bool italic = (font.Style & XFontStyle.Italic) != 0;
            bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0;
            bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0;
            bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
            bool underline = (font.Style & XFontStyle.Underline) != 0;

            Realize(font, brush, boldSimulation ? 2 : 0);

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

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

                case XStringAlignment.Far:
                    x += rect.Width - width;
                    break;
            }
            if (Gfx.PageDirection == XPageDirection.Downwards)
            {
                switch (format.LineAlignment)
                {
                    case XLineAlignment.Near:
                        y += cyAscent;
                        break;

                    case XLineAlignment.Center:
                        // TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
                        y += (cyAscent * 3 / 4) / 2 + rect.Height / 2;
                        break;

                    case XLineAlignment.Far:
                        y += -cyDescent + rect.Height;
                        break;

                    case XLineAlignment.BaseLine:
                        // Nothing to do.
                        break;
                }
            }
            else
            {
                switch (format.LineAlignment)
                {
                    case XLineAlignment.Near:
                        y += cyDescent;
                        break;

                    case XLineAlignment.Center:
                        // TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
                        y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
                        break;

                    case XLineAlignment.Far:
                        y += -cyAscent + rect.Height;
                        break;

                    case XLineAlignment.BaseLine:
                        // Nothing to do.
                        break;
                }
            }

            PdfFont realizedFont = _gfxState._realizedFont;
            Debug.Assert(realizedFont != null);
            realizedFont.AddChars(s);

            const string format2 = Config.SignificantFigures4;
            OpenTypeDescriptor descriptor = realizedFont.FontDescriptor._descriptor;

            string text = null;
            if (font.Unicode)
            {
                StringBuilder sb = new StringBuilder();
                bool isSymbolFont = descriptor.FontFace.cmap.symbol;
                for (int idx = 0; idx < s.Length; idx++)
                {
                    char ch = s[idx];
                    if (isSymbolFont)
                    {
                        // Remap ch for symbol fonts.
                        ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00));  // @@@ refactor
                    }
                    int glyphID = descriptor.CharCodeToGlyphIndex(ch);
                    sb.Append((char)glyphID);
                }
                s = sb.ToString();

                byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s);
                bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null);
                text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);
            }
            else
            {
                byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s);
                text = PdfEncoders.ToStringLiteral(bytes, false, null);
            }

            // Map absolute position to PDF world space.
            XPoint pos = new XPoint(x, y);
            pos = WorldToView(pos);

            double verticalOffset = 0;
            if (boldSimulation)
            {
                // Adjust baseline in case of bold simulation???
                // No, because this would change the center of the glyphs.
                //verticalOffset = font.Size * Const.BoldEmphasis / 2;
            }

#if ITALIC_SIMULATION
            if (italicSimulation)
            {
                if (_gfxState.ItalicSimulationOn)
                {
                    AdjustTdOffset(ref pos, verticalOffset, true);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td\n{2} Tj\n", pos.X, pos.Y, text);
                }
                else
                {
                    // Italic simulation is done by skewing characters 20° to the right.
                    XMatrix m = new XMatrix(1, 0, Const.ItalicSkewAngleSinus, 1, pos.X, pos.Y);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
                        m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
                    _gfxState.ItalicSimulationOn = true;
                    AdjustTdOffset(ref pos, verticalOffset, false);
                }
            }
            else
            {
                if (_gfxState.ItalicSimulationOn)
                {
                    XMatrix m = new XMatrix(1, 0, 0, 1, pos.X, pos.Y);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
                        m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
                    _gfxState.ItalicSimulationOn = false;
                    AdjustTdOffset(ref pos, verticalOffset, false);
                }
                else
                {
                    AdjustTdOffset(ref pos, verticalOffset, false);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
                }
            }
#else
                AdjustTextMatrix(ref pos);
                AppendFormat2("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
#endif
            if (underline)
            {
                double underlinePosition = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlinePosition / font.CellSpace;
                double underlineThickness = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlineThickness / font.CellSpace;
                //DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
                double underlineRectY = Gfx.PageDirection == XPageDirection.Downwards
                    ? y - underlinePosition
                    : y + underlinePosition - underlineThickness;
                DrawRectangle(null, brush, x, underlineRectY, width, underlineThickness);
            }

            if (strikeout)
            {
                double strikeoutPosition = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutPosition / font.CellSpace;
                double strikeoutSize = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutSize / font.CellSpace;
                //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
                double strikeoutRectY = Gfx.PageDirection == XPageDirection.Downwards
                    ? y - strikeoutPosition
                    : y + strikeoutPosition - strikeoutSize;
                DrawRectangle(null, brush, x, strikeoutRectY, width, strikeoutSize);
            }
        }
        public FileResult GerarRelatorio(int?id)
        {
            using (var doc = new PdfSharpCore.Pdf.PdfDocument()) {
                var page = doc.AddPage();
                page.Size        = PdfSharpCore.PageSize.A4;
                page.Orientation = PdfSharpCore.PageOrientation.Portrait;

                var grafics          = XGraphics.FromPdfPage(page);
                var corFonte         = XBrushes.Black;
                var textFormatter    = new XTextFormatter(grafics);
                var textJustify      = new XTextFormatter(grafics);
                var fonteOrganizacao = new XFont("Times New Roman", 12);
                var fonteTitulo      = new XFont("Times New Roman", 12, XFontStyle.Bold);
                var fonteDesc        = new XFont("Times New Roman", 8, XFontStyle.Bold);
                var titulo           = new XFont("Times New Roman", 10, XFontStyle.Bold);
                var fonteDetalhes    = new XFont("Times New Roman", 7);
                var fonteNegrito     = new XFont("Times New Roman", 12, XFontStyle.Bold);
                var logo             = @"C:\Logo.png";
                var qtdpaginas       = doc.PageCount;


                textFormatter.DrawString(qtdpaginas.ToString(), new XFont("Arial", 7), corFonte,
                                         new XRect(575, 825, page.Width, page.Height));

                List <JuntadaTermoCessao> dados = new List <JuntadaTermoCessao>();

                MySqlConnection con = new MySqlConnection();
                con.ConnectionString = c.ConexaoDados();
                con.Open();
                string          data    = DateTime.Now.ToShortDateString();
                MySqlCommand    command = new MySqlCommand("SELECT * FROM juntadatermocessao  WHERE  Id = '" + id + "'", con);
                MySqlDataReader reader  = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        dados.Add(new JuntadaTermoCessao()
                        {
                            Autos        = reader.GetString("Autos"),
                            Contrato     = reader.GetInt64("Contrato"),
                            Vara         = reader.GetString("Vara"),
                            Comarca      = reader.GetString("Comarca"),
                            Estado       = reader.GetString("Estado"),
                            Banco        = reader.GetString("Banco"),
                            Reu          = reader.GetString("Reu"),
                            BancoCedente = reader.GetString("BancoCedente"),
                            Oab          = reader.GetString("Oab"),
                            Data         = reader.GetString("Data")
                        });;
                    }
                    Console.WriteLine(data);
                }

                for (int i = 0; i < dados.Count; i++)
                {
                    //Imagem todo da pagina
                    XImage imagem = XImage.FromFile(logo);
                    grafics.DrawImage(imagem, 200, 40, 200, 80);

                    var topo =
                        "EXCELENTÍSSIMO SENHOR DOUTOR JUIZ DE DIREITO DA " + dados[i].Vara + " DA " + dados[i].Comarca + " – ESTADO DO " + dados[i].Estado;

                    var dadosAutos =
                        "Autos nº: " + dados[i].Autos + "\n" +
                        "Contrato nº: " + dados[i].Contrato;


                    var texto =
                        "                                 " + dados[i].Banco + ", já qualificado, conforme procuração anexa, vem, nos " +
                        "autos em epígrafe, que " + dados[i].BancoCedente + " litiga contra " + dados[i].Reu + ", já também devidamente " +
                        "qualificada, vem, por seu procurador signatário, respeitosamente, à Douta presença de Vossa Excelência, " +
                        "em atendimento ao despacho retro, REQUERER a juntada do comprovante da cessão do crédito, decorrente do " +
                        "contrato objeto da lide.\n \n \n" +

                        "                                 Diante deste fato, pugna a parte autora a admissão no polo ativo destes autos, " +
                        "como cessionária o " + dados[i].Banco + ", nos termos do artigo 567 II, " +
                        "do Código de Processo Civil, bem como sejam procedidas todas as anotações de estilo o cartório distribuidor e " +
                        "na autuação do feito, nos termos de termo de cessão específico acostado ao final.\n \n \n" +

                        "                                 Caso não seja o entendimento deste D. Juízo, requer de forma subsidiaria, " +
                        "que " + dados[i].Banco + ", figure como assistente litisconsorcial, com base no artigo 109, § 2ª, do CPC.\n \n \n" +

                        "                                 In fine, requer que todas as intimações se deem na forma prevista nos " +
                        "artigos 272 e 273 do NCPC, para que sejam publicadas apenas em nome da Dra. " +
                        "CRISTIANE BELLINATI GARCIA LOPES, " + dados[i].Oab + ", sob pena de nulidade da intimação, conforme previsto no " +
                        "artigo 280 do CPC.\n \n \n" +

                        "                                 Termos em que,\n" +
                        "                                 Pede deferimento.\n" +
                        "                                 Maringá / PR, " + dados[i].Data;


                    var oab =
                        "CRISTIANE BELINATI GARCIA LOPES\n" +
                        dados[i].Oab;

                    var enderecoRodape =
                        "Endereço: Rua João Paulino Vieira Filho, 625, 12º andar – Sala 1201\n" +
                        "Bairro: Zona 01 CEP: 87020-015 - Fone: (44) 3033-9291 / (44) 2103-9291\n" +
                        "Maringa/PR";

                    //Texto do Topo
                    textJustify.Alignment = XParagraphAlignment.Left;
                    XRect rectTopo = new XRect(48, 155, 490, page.Height);
                    textJustify.DrawString(topo, fonteTitulo, corFonte, rectTopo, XStringFormats.TopLeft);

                    //Dados do Contrato
                    textJustify.Alignment = XParagraphAlignment.Left;
                    XRect rectDados = new XRect(48, 230, 490, page.Height);
                    textJustify.DrawString(dadosAutos, fonteNegrito, corFonte, rectDados, XStringFormats.TopLeft);

                    //Dados do Texto
                    textJustify.Alignment = XParagraphAlignment.Justify;
                    XRect rectTexto = new XRect(48, 290, 490, page.Height);
                    textJustify.DrawString(texto, fonteOrganizacao, corFonte, rectTexto, XStringFormats.TopLeft);

                    //Texto OAB
                    textJustify.Alignment = XParagraphAlignment.Center;
                    XRect rectOab = new XRect(48, 680, 490, page.Height);
                    textJustify.DrawString(oab, fonteTitulo, corFonte, rectOab, XStringFormats.TopLeft);

                    textJustify.Alignment = XParagraphAlignment.Center;
                    XRect rectenderecoRodape = new XRect(48, 790, 490, page.Height);
                    textJustify.DrawString(enderecoRodape, fonteDetalhes, corFonte, rectenderecoRodape, XStringFormats.TopLeft);
                }

                using (MemoryStream stream = new MemoryStream()) {
                    var contentType = "application/pdf";
                    doc.Save(stream, false);
                    var nomeArquivo = "Juntada Termo de Cessão.pdf";
                    return(File(stream.ToArray(), contentType, nomeArquivo));
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Draws the axis title.
        /// </summary>
        internal override void Draw()
        {
            AxisRendererInfo      ari  = (AxisRendererInfo)_rendererParms.RendererInfo;
            AxisTitleRendererInfo atri = ari._axisTitleRendererInfo;

            if (atri.AxisTitleText != "")
            {
                XGraphics gfx = _rendererParms.Graphics;
                if (atri.AxisTitleOrientation != 0)
                {
                    XRect layout = atri.Rect;
                    layout.X = -(layout.Width / 2);
                    layout.Y = -(layout.Height / 2);

                    double x = 0;
                    switch (atri.AxisTitleAlignment)
                    {
                    case HorizontalAlignment.Center:
                        x = atri.X + atri.Width / 2;
                        break;

                    case HorizontalAlignment.Right:
                        x = atri.X + atri.Width - layout.Width / 2;
                        break;

                    case HorizontalAlignment.Left:
                    default:
                        x = atri.X;
                        break;
                    }

                    double y = 0;
                    switch (atri.AxisTitleVerticalAlignment)
                    {
                    case VerticalAlignment.Center:
                        y = atri.Y + atri.Height / 2;
                        break;

                    case VerticalAlignment.Bottom:
                        y = atri.Y + atri.Height - layout.Height / 2;
                        break;

                    case VerticalAlignment.Top:
                    default:
                        y = atri.Y;
                        break;
                    }

                    XStringFormat xsf = new XStringFormat();
                    xsf.Alignment     = XStringAlignment.Center;
                    xsf.LineAlignment = XLineAlignment.Center;

                    XGraphicsState state = gfx.Save();
                    gfx.TranslateTransform(x, y);
                    gfx.RotateTransform(-atri.AxisTitleOrientation);
                    gfx.DrawString(atri.AxisTitleText, atri.AxisTitleFont, atri.AxisTitleBrush, layout, xsf);
                    gfx.Restore(state);
                }
                else
                {
                    XStringFormat format = new XStringFormat();
                    switch (atri.AxisTitleAlignment)
                    {
                    case HorizontalAlignment.Center:
                        format.Alignment = XStringAlignment.Center;
                        break;

                    case HorizontalAlignment.Right:
                        format.Alignment = XStringAlignment.Far;
                        break;

                    case HorizontalAlignment.Left:
                    default:
                        format.Alignment = XStringAlignment.Near;
                        break;
                    }

                    switch (atri.AxisTitleVerticalAlignment)
                    {
                    case VerticalAlignment.Center:
                        format.LineAlignment = XLineAlignment.Center;
                        break;

                    case VerticalAlignment.Bottom:
                        format.LineAlignment = XLineAlignment.Far;
                        break;

                    case VerticalAlignment.Top:
                    default:
                        format.LineAlignment = XLineAlignment.Near;
                        break;
                    }

                    gfx.DrawString(atri.AxisTitleText, atri.AxisTitleFont, atri.AxisTitleBrush, atri.Rect, format);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Draws the legend.
        /// </summary>
        internal override void Draw()
        {
            ChartRendererInfo  cri = (ChartRendererInfo)_rendererParms.RendererInfo;
            LegendRendererInfo lri = cri.legendRendererInfo;

            if (lri == null)
            {
                return;
            }

            XGraphics          gfx   = _rendererParms.Graphics;
            RendererParameters parms = new RendererParameters();

            parms.Graphics = gfx;

            LegendEntryRenderer ler = new LegendEntryRenderer(parms);

            bool verticalLegend = (lri._legend._docking == DockingType.Left || lri._legend._docking == DockingType.Right);
            int  paddingFactor  = 1;

            if (lri.BorderPen != null)
            {
                paddingFactor = 2;
            }
            XRect legendRect = lri.Rect;

            legendRect.X += LeftPadding * paddingFactor;
            if (verticalLegend)
            {
                legendRect.Y = legendRect.Bottom - BottomPadding * paddingFactor;
            }
            else
            {
                legendRect.Y += TopPadding * paddingFactor;
            }

            foreach (LegendEntryRendererInfo leri in cri.legendRendererInfo.Entries)
            {
                if (verticalLegend)
                {
                    legendRect.Y -= leri.Height;
                }

                XRect entryRect = legendRect;
                entryRect.Width  = leri.Width;
                entryRect.Height = leri.Height;

                leri.Rect          = entryRect;
                parms.RendererInfo = leri;
                ler.Draw();

                if (verticalLegend)
                {
                    legendRect.Y -= EntrySpacing;
                }
                else
                {
                    legendRect.X += entryRect.Width + EntrySpacing;
                }
            }

            // Draw border around legend
            if (lri.BorderPen != null)
            {
                XRect borderRect = lri.Rect;
                borderRect.X      += LeftPadding;
                borderRect.Y      += TopPadding;
                borderRect.Width  -= LeftPadding + RightPadding;
                borderRect.Height -= TopPadding + BottomPadding;
                gfx.DrawRectangle(lri.BorderPen, borderRect);
            }
        }
Beispiel #12
0
        static void Main()
        {
            string imagePath1;

            imagePath1 = "H:/haixt111/图片/1Rose (RGB 8).tif";
            void AddLogo(XGraphics gfx, PdfPage page, string imagePath, int xPosition, int yPosition)
            {
                if (!File.Exists(imagePath))
                {
                    throw new FileNotFoundException(String.Format("Could not find image {0}.", imagePath));
                }

                XImage xImage = XImage.FromFile(imagePath);

                gfx.DrawImage(xImage, xPosition, yPosition, xImage.PixelWidth / 4.2, xImage.PixelWidth / 5.8); //3.24  5 /3.7, xImage.PixelWidth / 5.8
                                                                                                               //gfx.ScaleTransform(0.15);
            }

            string teststrr = " 数量";
            int    a        = teststrr.Length;

            if (a > 1)
            {
                MessageBox.Show("可以");
            }

            try
            {
                PdfDocument doc  = new PdfDocument();
                PdfPage     page = doc.AddPage();
                XGraphics   gfx  = XGraphics.FromPdfPage(page);
                AddLogo(gfx, page, imagePath1, 30, 365);

                //文字
                //字体黑体simhei.ttf
                string strFontPath = @"C:/Windows/Fonts/simhei.ttf";
                System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
                pfcFonts.AddFontFile(strFontPath);
                XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
                XFont           font    = new XFont(pfcFonts.Families[0], 15, XFontStyle.Regular, options);
                XFont           fontd   = new XFont(pfcFonts.Families[0], 20, XFontStyle.Regular, options);
                //字体华文仿宋STFANGSO.TTF
                string strFontPath1 = @"C:/Windows/Fonts/STFANGSO.TTF";
                System.Drawing.Text.PrivateFontCollection pfcFonts1 = new System.Drawing.Text.PrivateFontCollection();
                pfcFonts.AddFontFile(strFontPath1);
                XPdfFontOptions options1 = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
                XFont           font1    = new XFont(pfcFonts.Families[0], 15, XFontStyle.Regular, options);


                string st1 = "乳腺癌HER2基因荧光原位杂交(FISH)检测报告";
                gfx.DrawString(st1, fontd, XBrushes.Black,
                               new XRect(0, 10, page.Width, page.Height),
                               XStringFormats.TopCenter);//乳腺癌HE检测报告Center

                string st2 = "姓名:";
                gfx.DrawString(st2, font, XBrushes.Black,
                               new XRect(30, 50, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st3 = "性别:";
                gfx.DrawString(st3, font, XBrushes.Black,
                               new XRect(240, 50, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st4 = "年龄:";
                gfx.DrawString(st4, font, XBrushes.Black,
                               new XRect(430, 50, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st4d = "岁";
                gfx.DrawString(st4d, font, XBrushes.Black,
                               new XRect(510, 50, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st5 = "报告日期:";
                gfx.DrawString(st5, font, XBrushes.Black,
                               new XRect(30, 90, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st6 = "科别:";
                gfx.DrawString(st6, font, XBrushes.Black,
                               new XRect(300, 90, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st7 = "住院号:";
                gfx.DrawString(st7, font, XBrushes.Black,
                               new XRect(30, 130, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st8 = "病理号:";
                gfx.DrawString(st8, font, XBrushes.Black,
                               new XRect(300, 130, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st9 = "送检单位:";
                gfx.DrawString(st9, font, XBrushes.Black,
                               new XRect(30, 170, page.Width, page.Height),
                               XStringFormats.TopLeft);

                //检测结果
                string st10 = "检测结果:";
                gfx.DrawString(st10, font, XBrushes.Black,
                               new XRect(30, 210, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d1 = "HER2信号分布情况:";
                gfx.DrawString(st10d1, font1, XBrushes.Black,
                               new XRect(40, 230, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d2 = "点状分布:";
                gfx.DrawString(st10d2, font1, XBrushes.Black,
                               new XRect(40, 250, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d3 = "计数细胞个数:";
                gfx.DrawString(st10d3, font1, XBrushes.Black,
                               new XRect(120, 250, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string stq = "23";
                gfx.DrawString(stq, font, XBrushes.Black,
                               new XRect(220, 250, page.Width, page.Height),
                               XStringFormats.TopLeft);

                string st10d4 = "HER2信号总数:";
                gfx.DrawString(st10d4, font1, XBrushes.Black,
                               new XRect(330, 250, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d5 = "CSP17染色体信号数:";
                gfx.DrawString(st10d5, font1, XBrushes.Black,
                               new XRect(120, 270, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d6 = "HER2/CSP27比值:";
                gfx.DrawString(st10d6, font1, XBrushes.Black,
                               new XRect(330, 270, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d7 = "平均每个细胞HER2信号数:";
                gfx.DrawString(st10d7, font1, XBrushes.Black,
                               new XRect(120, 290, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st10d8 = "平均每个细胞CSP17信号数:";
                gfx.DrawString(st10d8, font1, XBrushes.Black,
                               new XRect(120, 310, page.Width, page.Height),
                               XStringFormats.TopLeft);
                //检测结果止

                string st11 = "结果附图:";
                gfx.DrawString(st11, font, XBrushes.Black,
                               new XRect(30, 340, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st12 = "结果评价:";
                gfx.DrawString(st12, font, XBrushes.Black,
                               new XRect(30, 650, page.Width, page.Height),
                               XStringFormats.TopLeft);
                string st13 = "报告医师:";
                gfx.DrawString(st13, font, XBrushes.Black,
                               new XRect(350, 800, page.Width, page.Height),
                               XStringFormats.TopLeft);
                //文字止

                //矩形格式框
                XTextFormatter tf    = new XTextFormatter(gfx);
                string         st12d = "评价内容";
                XRect          rect  = new XRect(30, 670, 550, 130);//30, 650, 550, 150);
                gfx.DrawRectangle(XBrushes.WhiteSmoke, rect);
                tf.Alignment = XParagraphAlignment.Left;
                tf.DrawString(st12d, font, XBrushes.Black, rect, XStringFormats.TopLeft);
                //矩形格式框止

                const string filename = "Hello test.pdf";
                doc.Save(filename);
                Process.Start(filename);
            }
            catch (Exception)
            {
                // Handle exception
            }
        }
Beispiel #13
0
 public override void Initialize()
 {
     // instantiate document
     pdfDocument = new PdfDocument();
     pdfDocument.Info.Title = title;
     pdfDocument.Info.Author = author;
     // add a page
     PdfPage page = pdfDocument.AddPage();
     page.Orientation = PageOrientation.Portrait;
     // set page size
     page.Width = XUnit.FromMillimeter(bbox.Width);
     page.Height = XUnit.FromMillimeter(bbox.Height);
     // get graphics
     this.pdfGfx = XGraphics.FromPdfPage(page);
     // draw a bounding box
     XRect rect = new XRect(0.5, 0.5, page.Width - 1, page.Height - 1);
     this.pdfGfx.DrawRectangle(XBrushes.White, rect);
     // initialize cotation
     PicCotation._globalCotationProperties._arrowLength = XUnit.FromMillimeter(bbox.Height) / 50.0;
 }
        /// <summary>
        /// Renders a thick or thin line for the bar code.
        /// </summary>
        /// <param name="info"></param>
        /// <param name="isThick">Determines whether a thick or a thin line is about to be rendered.</param>
        internal void RenderBar(BarCodeRenderInfo info, bool isThick)
        {
            double barWidth = GetBarWidth(info, isThick);
            double height = Size.Height;
            double xPos = info.CurrPos.X;
            double yPos = info.CurrPos.Y;

            switch (TextLocation)
            {
                case TextLocation.AboveEmbedded:
                    height -= info.Gfx.MeasureString(Text, info.Font).Height;
                    yPos += info.Gfx.MeasureString(Text, info.Font).Height;
                    break;
                case TextLocation.BelowEmbedded:
                    height -= info.Gfx.MeasureString(Text, info.Font).Height;
                    break;
            }

            XRect rect = new XRect(xPos, yPos, barWidth, height);
            info.Gfx.DrawRectangle(info.Brush, rect);
            info.CurrPos.X += barWidth;
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (radioFirst.Checked)
            {
                frame = XImage.FromFile("Resources\\first.png");
            }
            if (radioSecond.Checked)
            {
                frame = XImage.FromFile("Resources\\second.png");
            }
            if (radioThird.Checked)
            {
                frame = XImage.FromFile("Resources\\third.png");
            }

            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();

            page.Width  = 1748;
            page.Height = 1240;
            XGraphics gfx    = XGraphics.FromPdfPage(page);
            int       width  = this.photo.PixelWidth;
            int       height = this.photo.PixelHeight;

            gfx.DrawImage(this.photo, 0, 0, 1748, 1240);
            if (frame != null)
            {
                gfx.DrawImage(this.frame, 0, 0, 1748, 1240);
            }
            PdfPage pageR = document.AddPage();

            pageR.Width  = 1748;
            pageR.Height = 1240;
            XGraphics gfxR = XGraphics.FromPdfPage(pageR);

            gfxR.DrawImage(this.rewers, 0, 0, 1748, 1240);

            XFont font = new XFont(fontName, 32, XFontStyle.BoldItalic);
            var   tf   = new XTextFormatter(gfxR);
            var   rect = new XRect(50, 300, 800, 500);

            XPen xpen = new XPen(XColors.White, 0.4);

            gfxR.DrawRectangle(xpen, rect);

            XStringFormat format = new XStringFormat();

            format.LineAlignment = XLineAlignment.Near;
            format.Alignment     = XStringAlignment.Near;

            string data = dateTimePicker.Value.ToString(), wishes = tbWishes.Text, names = tbSenderName.Text + " " + tbSenderSurname.Text,
                   pref = tbReceiverTitle.Text, recNames = tbReceiverName.Text + " " + tbReceiverSurname.Text, street = tbReceiverStreet.Text,
                   post = tbReceiverPost.Text;

            data = data + ", " + tbCity.Text;
            gfxR.DrawString(data, font, XBrushes.Black,
                            new XRect(-940, 90, page.Width, page.Height), XStringFormats.TopRight);
            tf.DrawString(wishes, font, XBrushes.Black,
                          new XRect(rect.X + 5, rect.Y, rect.Width - 5, 500), format);
            gfxR.DrawString(names, font, XBrushes.Black,
                            new XRect(-940, 1000, page.Width, page.Height), XStringFormats.TopRight);
            gfxR.DrawString(pref, font, XBrushes.Black,
                            new XRect(1050, 600, page.Width, page.Height), XStringFormat.TopLeft);
            gfxR.DrawString(recNames, font, XBrushes.Black,
                            new XRect(1050, 735, page.Width, page.Height), XStringFormat.TopLeft);
            gfxR.DrawString(street, font, XBrushes.Black,
                            new XRect(1050, 870, page.Width, page.Height), XStringFormat.TopLeft);
            gfxR.DrawString(post, font, XBrushes.Black,
                            new XRect(1050, 1010, page.Width, page.Height), XStringFormat.TopLeft);


            while (File.Exists(saveFilename + ".pdf"))
            {
                saveFilename = saveFilename + "1";
            }
            saveFilename = saveFilename + ".pdf";
            document.Save(saveFilename + ".pdf");
            MessageBox.Show("Utworzono dokument w: " + saveFilename);
        }
Beispiel #16
0
        public void DrawString(XGraphics gfx, string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format)
        {
            double x = layoutRectangle.X;
            double y = layoutRectangle.Y;

            double lineSpace = font.GetHeight(gfx);
            double cyAscent  = lineSpace * font.cellAscent / font.cellSpace;
            double cyDescent = lineSpace * font.cellDescent / font.cellSpace;

            bool bold      = (font.Style & XFontStyle.Bold) != 0;
            bool italic    = (font.Style & XFontStyle.Italic) != 0;
            bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
            bool underline = (font.Style & XFontStyle.Underline) != 0;

            //FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), // WPFHACK
            //  FlowDirection.LeftToRight, font.typeface, font.Size, brush.RealizeWpfBrush());
            TextBlock textBlock = FontHelper.CreateTextBlock(text, null, font.Size, brush.RealizeWpfBrush());

            Canvas.SetLeft(textBlock, x);
            Canvas.SetTop(textBlock, y);

            //formattedText.SetTextDecorations(TextDecorations.OverLine);
            switch (format.Alignment)
            {
            case XStringAlignment.Near:
                // nothing to do, this is the default
                //formattedText.TextAlignment = TextAlignment.Left;
                break;

            case XStringAlignment.Center:
                x += layoutRectangle.Width / 2;
                textBlock.TextAlignment = TextAlignment.Center;
                break;

            case XStringAlignment.Far:
                x += layoutRectangle.Width;
                textBlock.TextAlignment = TextAlignment.Right;
                break;
            }
            if (gfx.PageDirection == XPageDirection.Downwards)
            {
                switch (format.LineAlignment)
                {
                case XLineAlignment.Near:
                    //y += cyAscent;
                    break;

                    //case XLineAlignment.Center:
                    //  // TODO use CapHeight. PDFlib also uses 3/4 of ascent
                    //  y += -formattedText.Baseline + (cyAscent * 1 / 3) + layoutRectangle.Height / 2;
                    //  //y += -formattedText.Baseline + (font.Size * font.Metrics.CapHeight / font.unitsPerEm / 2) + layoutRectangle.Height / 2;
                    //  break;

                    //case XLineAlignment.Far:
                    //  y += -formattedText.Baseline - cyDescent + layoutRectangle.Height;
                    //  break;

                    //case XLineAlignment.BaseLine:
                    //  y -= formattedText.Baseline;
                    //  break;
                }
            }
            else
            {
                // TODOWPF: make unit test
                switch (format.LineAlignment)
                {
                case XLineAlignment.Near:
                    //y += cyDescent;
                    break;

                case XLineAlignment.Center:
                    // TODO use CapHeight. PDFlib also uses 3/4 of ascent
                    //y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
                    break;

                case XLineAlignment.Far:
                    //y += -cyAscent + rect.Height;
                    break;

                case XLineAlignment.BaseLine:
                    // nothing to do
                    break;
                }
            }

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

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

            //if (underline)
            //{
            //  formattedText.FontStyle.SetTextDecorations(TextDecorations.Underline);
            //  //double underlinePosition = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlinePosition / font.cellSpace;
            //  //double underlineThickness = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlineThickness / font.cellSpace;
            //  //DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
            //}

            //if (strikeout)
            //{
            //  formattedText.SetTextDecorations(TextDecorations.Strikethrough);
            //  //double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace;
            //  //double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace;
            //  //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
            //}

            //formattedText
            _canvas.Children.Add(textBlock);
        }
Beispiel #17
0
        /// <summary>
        /// Draws the content of the column plot area.
        /// </summary>
        internal override void Draw()
        {
            ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo;

            XRect plotAreaBox = cri.plotAreaRendererInfo.Rect;

            if (plotAreaBox.IsEmpty)
            {
                return;
            }

            XGraphics gfx = this.rendererParms.Graphics;

            double xMin = cri.xAxisRendererInfo.MinimumScale;
            double xMax = cri.xAxisRendererInfo.MaximumScale;
            double yMin = cri.yAxisRendererInfo.MinimumScale;
            double yMax = cri.yAxisRendererInfo.MaximumScale;

            LineFormatRenderer lineFormatRenderer;

            // Under some circumstances it is possible that no zero base line will be drawn,
            // e. g. because of unfavourable minimum/maximum scale and/or major tick, so force to draw
            // a zero base line if necessary.
            if (cri.yAxisRendererInfo.MajorGridlinesLineFormat != null ||
                cri.yAxisRendererInfo.MinorGridlinesLineFormat != null)
            {
                if (yMin < 0 && yMax > 0)
                {
                    XPoint[] points = new XPoint[2];
                    points[0].X = xMin;
                    points[0].Y = 0;
                    points[1].X = xMax;
                    points[1].Y = 0;
                    cri.plotAreaRendererInfo.matrix.TransformPoints(points);

                    if (cri.yAxisRendererInfo.MinorGridlinesLineFormat != null)
                    {
                        lineFormatRenderer = new LineFormatRenderer(gfx, cri.yAxisRendererInfo.MinorGridlinesLineFormat);
                    }
                    else
                    {
                        lineFormatRenderer = new LineFormatRenderer(gfx, cri.yAxisRendererInfo.MajorGridlinesLineFormat);
                    }

                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            // Draw columns
            XGraphicsState state = gfx.Save();

            foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
            {
                foreach (ColumnRendererInfo column in sri.pointRendererInfos)
                {
                    // Do not draw column if value is outside yMin/yMax range. Clipping does not make sense.
                    if (IsDataInside(yMin, yMax, column.point.value))
                    {
                        XLinearGradientBrush brush = new XLinearGradientBrush(column.Rect.BottomLeft, column.Rect.TopLeft, _orange, _orangeGradientEnd);
                        gfx.DrawRectangle(brush, column.Rect);
                    }
                }
            }

            // Draw borders around column.
            // A border can overlap neighbor columns, so it is important to draw borders at the end.
            //foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
            //{
            //  foreach (ColumnRendererInfo column in sri.pointRendererInfos)
            //  {
            //    // Do not draw column if value is outside yMin/yMax range. Clipping does not make sense.
            //    if (IsDataInside(yMin, yMax, column.point.value) && column.LineFormat.Width > 0)
            //    {
            //      lineFormatRenderer = new LineFormatRenderer(gfx, column.LineFormat);
            //      lineFormatRenderer.DrawRectangle(column.Rect);
            //    }
            //  }
            //}
            gfx.Restore(state);
        }
Beispiel #18
0
        /// <summary>
        /// Builds the soft mask.
        /// </summary>
        PdfSoftMask BuildSoftMask(RadialGradientBrush brush)
        {
            Debug.Assert(brush.GradientStops.HasTransparency());

            XRect viewBox = new XRect(0, 0, 360, 480); // HACK
            //XForm xform = new XForm(Context.PdfDocument, viewBox);

            PdfFormXObject form = Context.PdfDocument.Internals.CreateIndirectObject <PdfFormXObject>();

#if DEBUG
            if (DevHelper.RenderComments)
            {
                form.Elements.SetString("/@comment", "This is the Form XObject of the soft mask");
            }
#endif
            form.Elements.SetRectangle(PdfFormXObject.Keys.BBox, new PdfRectangle(viewBox));


            // Transparency group of mask form
            //<<
            //  /CS /DeviceGray
            //  /I false
            //  /K false
            //  /S /Transparency
            //  /Type /Group
            //>>
            PdfTransparencyGroupAttributes tgAttributes = Context.PdfDocument.Internals.CreateIndirectObject <PdfTransparencyGroupAttributes>();
            tgAttributes.Elements.SetName(PdfTransparencyGroupAttributes.Keys.CS, "/DeviceGray");
            tgAttributes.Elements.SetBoolean(PdfTransparencyGroupAttributes.Keys.I, false);
            tgAttributes.Elements.SetBoolean(PdfTransparencyGroupAttributes.Keys.K, false);

            // ExtGState of mask form
            //<<
            //  /AIS false
            //  /BM /Normal
            //  /ca 1
            //  /CA 1
            //  /op false
            //  /OP false
            //  /OPM 1
            //  /SA true
            //  /SMask /None
            //  /Type /ExtGState
            //>>
            PdfExtGState pdfStateMaskFrom = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>();
            pdfStateMaskFrom.SetDefault1();

            // Shading of mask form
            PdfShading shadingFrom = BuildShadingForSoftMask(brush);

            ////// Set reference to transparency group attributes
            ////pdfForm.Elements.SetObject(PdfFormXObject.Keys.Group, tgAttributes);
            ////pdfForm.Elements[PdfFormXObject.Keys.Matrix] = new PdfLiteral("[1.001 0 0 1.001 0.001 0.001]");

            // Soft mask
            //<<
            //  /G 21 0 R   % form
            //  /S /Luminosity
            //  /Type /Mask
            //>>
            PdfSoftMask softmask = Context.PdfDocument.Internals.CreateIndirectObject <PdfSoftMask>(); // new PdfSoftMask(this.writer.Owner);
            //extGState.Elements.SetReference(PdfExtGState.Keys.SMask, softmask);
            //this.writer.Owner.Internals.AddObject(softmask);
#if DEBUG
            if (DevHelper.RenderComments)
            {
                softmask.Elements.SetString("/@comment", "This is the soft mask");
            }
#endif
            softmask.Elements.SetName(PdfSoftMask.Keys.S, "/Luminosity");
            softmask.Elements.SetReference(PdfSoftMask.Keys.G, form);

            // Create content of mask form
            //<<
            //  /BBox [200.118 369.142 582.795 -141.094]
            //  /Group 16 0 R
            //  /Length 121
            //  /Matrix [1 0 0 1 0 0]
            //  /Resources
            //  <<
            //    /ExtGState
            //    <<
            //      /GS0 20 0 R
            //    >>
            //    /Shading
            //    <<
            //      /Sh0 19 0 R
            //    >>
            //  >>
            //  /Subtype /Form
            //>>
            //stream
            //  q
            //    200.118 369.142 382.677 -510.236 re
            //    W n
            //  q
            //    0 g
            //    1 i
            //    GS0 gs
            //    0.75 0 0 -0.75 200.1181183 369.1417236 cm
            //   BX /Sh0 sh EX Q
            //  Q
            //endstream
            form.Elements.SetReference(PdfFormXObject.Keys.Group, tgAttributes);
            PdfContentWriter writer = new PdfContentWriter(Context, form);
            writer.BeginContentRaw();
            // Acrobat 8 clips to bounding box, so we should do
            // why   0 480 360 -480 re ??
            //writer.WriteClip(bbox);
            //writer.WriteGraphicsState(extGState);
            writer.WriteLiteral("1 i 0 g\n");
            writer.WriteLiteral(writer.Resources.AddExtGState(pdfStateMaskFrom) + " gs\n");

            XMatrix transform = new XMatrix(); //(brush.Viewport.Width / viewBoxForm.width, 0, 0, brush.Viewport.Height / viewBoxForm.height, 0, 0);
            writer.WriteMatrix(transform);
            writer.WriteLiteral("BX " + writer.Resources.AddShading(shadingFrom) + " sh EX\n");
            writer.EndContent();

            return(softmask);
        }
Beispiel #19
0
 public void BeginContainer(XGraphicsContainer container, XRect dstrect, XRect srcrect, XGraphicsUnit unit)
 {
     // Before saving, the current transformation matrix must be completely realized.
     BeginGraphicMode();
     RealizeTransform();
     _gfxState.InternalState = container.InternalState;
     SaveState();
 }
Beispiel #20
0
 /// <summary>
 /// Convert from WinForms rectangle to core rectangle.
 /// </summary>
 public static RRect Convert(XRect r)
 {
     return(new RRect(r.X, r.Y, r.Width, r.Height));
 }
    // ----- DrawString ---------------------------------------------------------------------------

    public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format)
    {
      Realize(font, brush, 0);

      double x = rect.X;
      double y = rect.Y;

      double lineSpace = font.GetHeight(this.gfx);
      //int cellSpace = font.cellSpace; // font.FontFamily.GetLineSpacing(font.Style);
      //int cellAscent = font.cellAscent; // font.FontFamily.GetCellAscent(font.Style);
      //int cellDescent = font.cellDescent; // font.FontFamily.GetCellDescent(font.Style);
      //double cyAscent = lineSpace * cellAscent / cellSpace;
      //double cyDescent = lineSpace * cellDescent / cellSpace;
      double cyAscent = lineSpace * font.cellAscent / font.cellSpace;
      double cyDescent = lineSpace * font.cellDescent / font.cellSpace;
      double width = this.gfx.MeasureString(s, font).Width;

      bool bold = (font.Style & XFontStyle.Bold) != 0;
      bool italic = (font.Style & XFontStyle.Italic) != 0;
      bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
      bool underline = (font.Style & XFontStyle.Underline) != 0;

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

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

        case XStringAlignment.Far:
          x += rect.Width - width;
          break;
      }
      if (Gfx.PageDirection == XPageDirection.Downwards)
      {
        switch (format.LineAlignment)
        {
          case XLineAlignment.Near:
            y += cyAscent;
            break;

          case XLineAlignment.Center:
            // TODO use CapHeight. PDFlib also uses 3/4 of ascent
            y += (cyAscent * 3 / 4) / 2 + rect.Height / 2;
            break;

          case XLineAlignment.Far:
            y += -cyDescent + rect.Height;
            break;

          case XLineAlignment.BaseLine:
            // nothing to do
            break;
        }
      }
      else
      {
        switch (format.LineAlignment)
        {
          case XLineAlignment.Near:
            y += cyDescent;
            break;

          case XLineAlignment.Center:
            // TODO use CapHeight. PDFlib also uses 3/4 of ascent
            y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
            break;

          case XLineAlignment.Far:
            y += -cyAscent + rect.Height;
            break;

          case XLineAlignment.BaseLine:
            // nothing to do
            break;
        }
      }

      PdfFont realizedFont = this.gfxState.realizedFont;
      Debug.Assert(realizedFont != null);
      realizedFont.AddChars(s);

      OpenTypeDescriptor descriptor = realizedFont.FontDescriptor.descriptor;

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

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

      if (font.Unicode)
      {
        string s2 = "";
        for (int idx = 0; idx < s.Length; idx++)
        {
          char ch = s[idx];
          int glyphID = 0;
          if (descriptor.fontData.cmap.symbol)
          {
            glyphID = (int)ch + (descriptor.fontData.os2.usFirstCharIndex & 0xFF00);
            glyphID = descriptor.CharCodeToGlyphIndex((char)glyphID);
          }
          else
            glyphID = descriptor.CharCodeToGlyphIndex(ch);
          s2 += (char)glyphID;
        }
        s = s2;

        byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s);
        bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null);
        string text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);
        XPoint pos = new XPoint(x, y);
        AdjustTextMatrix(ref pos);
        AppendFormat(
          "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y, text);
        //PdfEncoders.ToStringLiteral(s, PdfStringEncoding.RawEncoding, null));
      }
      else
      {
        byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s);
        XPoint pos = new XPoint(x, y);
        AdjustTextMatrix(ref pos);
        AppendFormat(
          "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y,
          PdfEncoders.ToStringLiteral(bytes, false, null));
      }

      if (underline)
      {
        double underlinePosition = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlinePosition / font.cellSpace;
        double underlineThickness = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlineThickness / font.cellSpace;
        DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
      }

      if (strikeout)
      {
        double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace;
        double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace;
        DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
      }
    }
Beispiel #22
0
        public async Task <IActionResult> CreatePDF(int TemplateId)
        {
            Template template = await db.Template.Include(u => u.User).FirstOrDefaultAsync(x => x.Id == TemplateId);

            string UserName = db.GetUserName(HttpContext);

            if (template != null)
            {
                if ((template.User != null && template.User.Login == UserName) || template.Name == UserName)
                {
                    var         data     = JsonSerializer.Deserialize <TemplateSerializer>(template.JsonTemplate);
                    PdfDocument document = new PdfDocument();
                    document.Options.ColorMode = PdfColorMode.Cmyk;
                    PdfPage page = document.AddPage();
                    page.Width  = data.Width;
                    page.Height = data.Height;
                    XGraphics gfx = XGraphics.FromPdfPage(page);
                    for (int i = 0; i < data.Images.Count(); i++)
                    {
                        string path  = _env.WebRootPath + data.Images[i].Src.Replace('/', '\\');
                        XImage image = XImage.FromFile(path);
                        gfx.DrawImage(image, data.Images[i].Left, data.Images[i].Top, data.Images[i].Width, data.Images[i].Height);
                        //byte[] ImageByte = Convert.FromBase64String(data.Images[i].Src);
                        //using (var stream = new MemoryStream(ImageByte, 0, ImageByte.Length))
                        //{
                        //    XImage image = XImage.FromStream(stream);
                        //    gfx.DrawImage(image, data.Images[i].Left, data.Images[i].Top, data.Images[i].Width, data.Images[i].Height);
                        //}
                    }
                    for (int i = 0; i < data.TextBlocks.Count(); i++)
                    {
                        for (int j = 0; j < data.TextBlocks[i].Lines.Count(); j++)
                        {
                            Line line = data.TextBlocks[i].Lines[j];
                            for (int k = 0; k < line.Text.Count(); k++)
                            {
                                TextPart text = line.Text[k];
                                XRect    rect = new XRect(text.Left, text.Top, text.Width, text.Height);
                                gfx.DrawRectangle(XBrushes.Transparent, rect);
                                XTextFormatter tf        = new XTextFormatter(gfx);
                                XFontStyle     FontStyle = XFontStyle.Regular;
                                if (text.FontWeight == 700)
                                {
                                    FontStyle = XFontStyle.Bold;
                                }
                                if (text.FontStyle == "italic")
                                {
                                    FontStyle |= XFontStyle.Italic;
                                }
                                if (text.TextDecorationLine == "underline")
                                {
                                    FontStyle |= XFontStyle.Underline;
                                }
                                XFont font = new XFont(text.FontFamily, text.FontSize, FontStyle);
                                if (text.TextAlign == "left")
                                {
                                    tf.Alignment = XParagraphAlignment.Left;
                                }
                                if (text.TextAlign == "right")
                                {
                                    tf.Alignment = XParagraphAlignment.Right;
                                }
                                if (text.TextAlign == "center")
                                {
                                    tf.Alignment = XParagraphAlignment.Center;
                                }
                                tf.DrawString(text.Data, font, XBrushes.Black, rect, XStringFormats.TopLeft);
                            }
                        }
                    }
                    string filename = _env.WebRootPath + "/PdfDocuments/Template" + TemplateId + ".pdf";
                    document.Save(filename);
                    return(new PhysicalFileResult(filename, "application/pdf"));
                }
                return(StatusCode(StatusCodes.Status403Forbidden));
            }
            return(StatusCode(StatusCodes.Status404NotFound));
        }
Beispiel #23
0
 /// <summary>
 /// Renders a single line of the character. Each character has three lines and three spaces
 /// </summary>
 /// <param name="info">
 /// </param>
 /// <param name="barWidth">
 /// Indicates the thickness of the line/bar to be rendered. 
 /// </param>
 /// <param name="brush">
 /// Indicates the brush to use to render the line/bar. 
 /// </param>
 private void RenderBar(BarCodeRenderInfo info, double barWidth, XBrush brush)
 {
     double height = this.Size.Height;
     double yPos = info.CurrPos.Y;
     switch (this.TextLocation)
     {
         case TextLocation.Above:
             yPos = info.CurrPos.Y + (height / 5);
             height *= 4.0 / 5;
             break;
         case TextLocation.Below:
             height *= 4.0 / 5;
             break;
         case TextLocation.AboveEmbedded:
         case TextLocation.BelowEmbedded:
         case TextLocation.None:
             break;
     }
     XRect rect = new XRect(info.CurrPos.X, yPos, barWidth, height);
     info.Gfx.DrawRectangle(brush, rect);
     info.CurrPos.X += barWidth;
 }
Beispiel #24
0
        /// <summary>
        /// Generates report and stores it in the given path then returns the string on return so that the report can be opened and viewd if needed;
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public async Task <string> generateReport(string reportType, DataGrid dg, string custID, int timespan, DateTime startDate, bool automatic, string path)
        {
            //records Auto generation
            if (automatic)
            {
                await this.InQuery("INSERT INTO ReportHistory (report_date, report_type, automatically_generated, DateOfNext, timeSpan, savePath, userID) VALUES (@val0, @val1, @val2, @val3, @val4, @val5, @val6)", DateTime.Now.Date, reportType, automatic, DateTime.Now.Date.AddDays(timespan), timespan, path, custID);
            }
            //records generation
            else
            {
                await this.InQuery("INSERT INTO ReportHistory (report_date, report_type, automatically_generated, timespan,userID) VALUES (@val0, @val1, @val2,@val3, @val4)", DateTime.Now.Date, reportType, automatic, timespan, custID);
            }

            var endDate = startDate.AddDays(timespan);

            DateTime time        = DateTime.Now;
            int      year        = time.Year;
            int      month       = time.Month;
            int      day         = time.Day;
            int      hour        = time.Hour;
            int      minute      = time.Minute;
            int      second      = time.Second;
            int      millisecond = time.Millisecond;

            path += year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".pdf";

            //query used to create diffrent report types
            switch (reportType)
            {
            case "Individual Performance":
                await this.Select(dg,
                                  "SELECT first_name, last_name, tasks.location AS Department, job_completed AS Date, start_time, time_taken, t1.total_time AS Total " +
                                  "FROM staff, job, Job_Tasks, Tasks, " +
                                  "( SELECT SUM(time_taken) as total_time, Staffstaff_ID AS totalStaffID  " +
                                  "FROM Job_Tasks, job  " +
                                  "WHERE job_status = \"Completed\"  " +
                                  "AND Job_number = Jobjob_number  " +
                                  "AND job_completed BETWEEN @val0 AND @val1  " +
                                  "GROUP BY Staffstaff_ID) t1  " +
                                  "WHERE staff_ID = Staffstaff_ID  " +
                                  "AND t1.totalStaffID = staff_ID  " +
                                  "AND Job_number = Jobjob_number  " +
                                  "AND Taskstask_ID = task_ID  " +
                                  "AND job_status = \"Completed\"  " +
                                  "AND job_completed BETWEEN @val0 AND @val1; "
                                  , startDate, endDate);

                break;

            case "Summary Performance":
                await this.Select(dg,
                                  "SELECT * " +
                                  "FROM v1 " +
                                  "WHERE Date BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Day Shift 1\" " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, ' '), coalesce(NULL, 'Total'), coalesce(SUM(Copy_room), '0'), coalesce(Sum(Development), '0'), coalesce(Sum(Finishing), '0'), coalesce(Sum(Packing), '0') " +
                                  "FROM v1 " +
                                  "WHERE DATE BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Day Shift 1\" " +
                                  "UNION " +
                                  "SELECT * " +
                                  "FROM v1 " +
                                  "WHERE Date BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Day Shift 2\" " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, ' '), coalesce(NULL, 'Total'), coalesce(SUM(Copy_room), '0'), coalesce(Sum(Development), '0'), coalesce(Sum(Finishing), '0'), coalesce(Sum(Packing), '0') " +
                                  "FROM v1 " +
                                  "WHERE DATE BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Day Shift 2\" " +
                                  "UNION " +
                                  "SELECT * " +
                                  "FROM v1 " +
                                  "WHERE Date BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Night Shift 1\" " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, ' '), coalesce(NULL, 'Total'), coalesce(SUM(Copy_room), '0'), coalesce(Sum(Development), '0'), coalesce(Sum(Finishing), '0'), coalesce(Sum(Packing), '0') " +
                                  "FROM v1 " +
                                  "WHERE DATE BETWEEN @val0 AND @val1 " +
                                  "AND Shift = \"Night Shift 1\" " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, ' '), coalesce(NULL, ' '), coalesce(NULL, ' '), coalesce(NULL, ' '), coalesce(NULL, ' '), coalesce(NULL, ' ') " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, ' '), Shift, coalesce(SUM(Copy_room), '0'), coalesce(Sum(Development), '0'), coalesce(Sum(Finishing), '0'), coalesce(Sum(Packing), '0') " +
                                  "FROM v1 " +
                                  "WHERE DATE BETWEEN @val0 AND @val1 " +
                                  "GROUP BY Shift " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, 'Total '), coalesce(NULL, ' '), coalesce(SUM(Copy_room), '0'), coalesce(Sum(Development), '0'), coalesce(Sum(Finishing), '0'), coalesce(Sum(Packing), '0') " +
                                  "FROM v1 " +
                                  "WHERE DATE BETWEEN @val0 AND @val1; "
                                  , startDate, endDate);

                break;

            case "Individual":
                await this.Select(dg,
                                  "SELECT DISTINCT(job_number), job_priority, job_status, special_instructions AS instructions, job_completed, discounted_total AS price " +
                                  "FROM Job, Customer " +
                                  "WHERE CustomerAccount_number = account_number " +
                                  "AND Customerphone_number = @val0 " +
                                  "AND deadline BETWEEN @val1 AND @val2 " +
                                  "UNION " +
                                  "SELECT coalesce(NULL, 'Total Jobs Booked: '), COUNT(job_number), coalesce(NULL, '---'), coalesce(NULL, '----'), coalesce(NULL, 'Total Paid: '), SUM(discounted_Total) " +
                                  "FROM Job,customer " +
                                  "WHERE CustomerAccount_number = account_number " +
                                  "AND Customerphone_number = @val0 " +
                                  "AND deadline BETWEEN @val1 AND @val2 " +
                                  ";"
                                  , int.Parse(custID), startDate, endDate);

                break;

            default:
                MessageBox.Show("There was an error");
                break;
            }
            //printing the query into a pdf document
            PdfDocument document = new PdfDocument();

            document.Info.Title = "Report";
            reportType         += " Report:";

            // creates extra pages if query is too long
            PdfPage page = document.AddPage();

            page.Height = 842;//842
            page.Width  = 590;

            XGraphics gfx = XGraphics.FromPdfPage(page);

            XFont font = new XFont("Verdana", 14, XFontStyle.Bold);
            XRect rect = new XRect(new XPoint(), gfx.PageSize);

            rect.Inflate(-10, -15);

            gfx.DrawString(reportType, font, XBrushes.MidnightBlue, rect, XStringFormats.TopCenter);

            XStringFormat format = new XStringFormat();

            format.LineAlignment = XLineAlignment.Far;
            format.Alignment     = XStringAlignment.Center;
            font = new XFont("Verdana", 8);

            document.Outlines.Add(reportType, page, true);

            // Text format
            format.LineAlignment = XLineAlignment.Near;
            format.Alignment     = XStringAlignment.Near;
            XFont fontParagraph = new XFont("Verdana", 8, XFontStyle.Regular);


            // page structure options
            double lineHeight = 20;
            int    marginLeft = 20;
            int    marginTop  = 100;

            // Row elements
            int el_width  = 40;
            int el_height = 15;

            DataTable dt = new DataTable();

            dt = ((DataView)dg.ItemsSource).ToTable();

            List <string> l = dt.Columns.Cast <DataColumn>().Select(x => x.ColumnName).ToList();

            CreateTable(page, dt, gfx, format, lineHeight, marginLeft, marginTop, el_height, el_width);

            document.Save(path);
            return(path);
        }
Beispiel #25
0
        ///<summary>The pdfSharp version of drawstring.  g is used for measurement.  scaleToPix scales xObjects to pixels.</summary>
        public static void DrawStringX(XGraphics xg, Graphics g, double scaleToPix, string str, XFont xfont, XBrush xbrush, XRect xbounds)
        {
            //There are two coordinate systems here: pixels (used by us) and points (used by PdfSharp).
            //MeasureString and ALL related measurement functions must use pixels.
            //DrawString is the ONLY function that uses points.
            //pixels:
            Rectangle bounds = new Rectangle((int)(scaleToPix * xbounds.Left),
                                             (int)(scaleToPix * xbounds.Top),
                                             (int)(scaleToPix * xbounds.Width),
                                             (int)(scaleToPix * xbounds.Height));
            FontStyle fontstyle = FontStyle.Regular;

            if (xfont.Style == XFontStyle.Bold)
            {
                fontstyle = FontStyle.Bold;
            }
            //pixels: (except Size is em-size)
            Font font = new Font(xfont.Name, (float)xfont.Size, fontstyle);
            //pixels:
            SizeF        fit    = new SizeF((float)(bounds.Width - rightPad), (float)(font.Height));
            StringFormat format = StringFormat.GenericTypographic;
            //pixels:
            float pixelsPerLine = LineSpacingForFont(font.Name) * (float)font.Height;
            float lineIdx       = 0;
            int   chars;
            int   lines;
            //points:
            RectangleF layoutRectangle;

            for (int ix = 0; ix < str.Length; ix += chars)
            {
                if (bounds.Y + topPad + pixelsPerLine * lineIdx > bounds.Bottom)
                {
                    break;
                }
                //pixels:
                g.MeasureString(str.Substring(ix), font, fit, format, out chars, out lines);
                //PdfSharp isn't smart enough to cut off the lower half of a line.
                //if(bounds.Y+topPad+pixelsPerLine*lineIdx+font.Height > bounds.Bottom) {
                //	layoutH=bounds.Bottom-(bounds.Y+topPad+pixelsPerLine*lineIdx);
                //}
                //else {
                //	layoutH=font.Height+2;
                //}
                //use points here:
                float adjustTextDown = 10f;              //this value was arrived at by trial and error.
                layoutRectangle = new RectangleF(
                    (float)xbounds.X,
                    //(float)(xbounds.Y+(float)topPad/scaleToPix+(pixelsPerLine/scaleToPix)*lineIdx),
                    (float)(xbounds.Y + adjustTextDown + (pixelsPerLine / scaleToPix) * lineIdx),
                    (float)xbounds.Width + 50, //any amount of extra padding here will not cause malfunction
                    0);                        //layoutH);
                xg.DrawString(str.Substring(ix, chars), xfont, xbrush, (double)layoutRectangle.Left, (double)layoutRectangle.Top);
                lineIdx += 1;
            }
        }
Beispiel #26
0
        /// <summary>
        /// CreatePDF
        /// </summary>
        /// <param name="attestation"></param>
        /// <param name="textBox_titre_attestation"></param>
        /// <param name="textBox_message"></param>
        /// <param name="executablePath"></param>
        /// <returns>Chemin du fichier généré</returns>
        public static string CreatePDF(KeyValuePair <int, Attestation> attestation, string textBox_titre_attestation, string textBox_message, string executablePath)
        {
            try
            {
                // Create a new PDF document
                PdfSharp.Pdf.PdfDocument document = new PdfDocument();
                document.Info.Title = $"abonnement {attestation.Value.RaisonSociale}";

                // Create an empty page
                PdfPage page = document.AddPage();

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

                DrawImage(gfx, "logo.jpg", 50, 50, 197, 170);

                // Create a font
                XFont font_normal = new XFont("Trebuchet MS", 12, XFontStyle.Regular);
                XFont font_titre  = new XFont("Trebuchet MS", 14, XFontStyle.Bold);

                // Bloc adresse
                //gfx.DrawString(CIVILITE + " " + INTERLOCUTEUR, font_normal, XBrushes.Black, new XRect(350, 100, 0, 0), XStringFormats.Default);
                gfx.DrawString(attestation.Value.RaisonSociale, font_normal, XBrushes.Black, new XRect(350, 120, 0, 0), XStringFormats.Default);
                gfx.DrawString(attestation.Value.AdresseLigne1, font_normal, XBrushes.Black, new XRect(350, 140, 0, 0), XStringFormats.Default);
                gfx.DrawString(attestation.Value.AdresseCP + " " + attestation.Value.AdresseVille, font_normal, XBrushes.Black, new XRect(350, 160, 0, 0), XStringFormats.Default);

                // Titre
                gfx.DrawString(textBox_titre_attestation, font_titre, XBrushes.Black, new XRect(240, 300, 0, 0), XStringFormats.Default);

                string message = textBox_message;
                message = message.Replace("{RAISON_SOCIALE}", attestation.Value.RaisonSociale);
                message = message.Replace("{ADRESSE_LIGNE1}", attestation.Value.AdresseLigne1);
                message = message.Replace("{CP}", attestation.Value.AdresseCP);
                message = message.Replace("{VILLE}", attestation.Value.AdresseVille);
                message = message.Replace("{HEURE}", attestation.Value.Heure);
                message = message.Replace("{CIVILITE}", attestation.Value.Civilite);
                message = message.Replace("{INTERLOCUTEUR}", attestation.Value.Interlocuteur);

                XRect rect = new XRect(50, 350, 500, 400);

                // gfx.DrawRectangle(XBrushes.SeaShell, rect);
                XTextFormatter tf = new XTextFormatter(gfx);
                tf.DrawString(message, font_normal, XBrushes.Black, rect, XStringFormats.TopLeft);

                // gfx.DrawString(message, font_normal, XBrushes.Black, rect, XStringFormats.TopLeft);
                string filename = $"{textBox_titre_attestation}-{attestation.Key}-{attestation.Value.RaisonSociale}.pdf";

                filename = CleanBadChar(filename);

                System.IO.Directory.CreateDirectory(@".\Temp\");
                string filePath = Path.GetDirectoryName(executablePath) + @"\Temp\" + filename;

                NettoyagePDF(filePath);

                document.Save(filePath);

                return(filePath);
            }
            catch (Exception ex)
            {
                throw new Exception("Erreur de génération du PDF", ex);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Prepares a given text for drawing, performs the layout, returns the index of the last fitting char and the needed height.
        /// </summary>
        /// <param name="text">The text to be drawn.</param>
        /// <param name="font">The font to be used.</param>
        /// <param name="layoutRectangle">The layout rectangle. Set the correct width.
        /// Either set the available height to find how many chars will fit.
        /// Or set height to double.MaxValue to find which height will be needed to draw the whole text.</param>
        /// <param name="lastFittingChar">Index of the last fitting character. Can be -1 if the character was not determined. Will be -1 if the whole text can be drawn.</param>
        /// <param name="neededHeight">The needed height - either for the complete text or the used height of the given rect.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public void PrepareDrawString(string text, XFont font, XRect layoutRectangle, out int lastFittingChar, out double neededHeight)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            if (font == null)
            {
                throw new ArgumentNullException("font");
            }

            Text            = text;
            Font            = font;
            LayoutRectangle = layoutRectangle;

            lastFittingChar = -1;
            neededHeight    = double.MinValue;

            if (text.Length == 0)
            {
                return;
            }

            CreateBlocks();

            CreateLayout();

            preparedText = true;

            double dy    = cyDescent + cyAscent;
            int    count = this.blocks.Count;

            for (int idx = 0; idx < count; idx++)
            {
                Block block = (Block)this.blocks[idx];
                if (block.Stop)
                {
                    // We have a Stop block, so only part of the text will fit. We return the index of the last fitting char (and the height of the block, if available).
                    lastFittingChar = 0;
                    int idx2 = idx - 1;
                    while (idx2 >= 0)
                    {
                        Block block2 = (Block)this.blocks[idx2];
                        if (block2.EndIndex >= 0)
                        {
                            lastFittingChar = block2.EndIndex;
                            neededHeight    = dy + block2.Location.y; // Test this!!!!!
                            return;
                        }
                        --idx2;
                    }
                    return;
                }
                if (block.Type == BlockType.LineBreak)
                {
                    continue;
                }
                //gfx.DrawString(block.Text, font, brush, dx + block.Location.x, dy + block.Location.y);
                neededHeight = dy + block.Location.y; // Test this!!!!! Performance optimization?
            }
        }
Beispiel #28
0
 public virtual void Draw(Context context, XGraphics gfx, XRect bounds, T card, PrintOptions options)
 {
     throw new NotImplementedException();
 }
        public static void Test(PdfSharp.Drawing.XGraphics gfx)
        {
            XRect  rect;
            XPen   pen;
            double x = 50, y = 100;
            XFont  fontH1     = new XFont("Times", 18, XFontStyle.Bold);
            XFont  font       = new XFont("Times", 12);
            XFont  fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);
            double ls         = font.GetHeight(gfx);

            // 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
            pen           = new XPen(XColors.Red, 4);
            pen.DashStyle = XDashStyle.Dash;
            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

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

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

            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen  = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor(System.Drawing.KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush 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;
            XGraphicsState state   = gfx.Save();
            XRect          rcImage = new XRect(100, y, 100, 100 * System.Math.Sqrt(2));

            gfx.DrawRectangle(XBrushes.Snow, rcImage);
            gfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), rcImage);
            gfx.Restore(state);
        }
Beispiel #30
0
        protected static void DrawBorderedText(XGraphics gfx, string text, XFont font, XBrush mainBrush, XBrush backBrush, XRect centerRect, XRect bounds, float offset)
        {
            for (int i = -1; i < 2; i++)
            {
                for (int j = -1; j < 2; j++)
                {
                    float borderOffset = offset;
                    //if (i != 0 && j != 0)
                    //    borderOffset *= .7f;

                    XRect borderRect = centerRect + new XPoint(i * borderOffset, j * borderOffset);

                    gfx.DrawString(text, font, backBrush, ScaleRect(borderRect, bounds), XStringFormats.Center);
                }
            }

            gfx.DrawString(text, font, mainBrush, ScaleRect(centerRect, bounds), XStringFormats.Center);
        }
Beispiel #31
0
 /// <summary>
 /// Init.
 /// </summary>
 public XTextureBrush(XImage image, XRect dstRect, XPoint translateTransformLocation)
 {
     _image   = image;
     _dstRect = dstRect;
     _translateTransformLocation = translateTransformLocation;
 }
Beispiel #32
0
        static void Main()
        {
            // Get a fresh copy of the sample PDF file
            string filename = "Portable Document Format.pdf";

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

            // Create the output document
            PdfDocument outputDocument = new PdfDocument();

            // Show single pages
            // (Note: one page contains two pages from the source document)
            outputDocument.PageLayout = PdfPageLayout.SinglePage;

            XFont         font   = new XFont("Verdana", 8, XFontStyle.Bold);
            XStringFormat format = new XStringFormat();

            format.Alignment     = XStringAlignment.Center;
            format.LineAlignment = XLineAlignment.Far;
            XGraphics gfx;
            XRect     box;

            // Open the external document as XPdfForm object
            XPdfForm form = XPdfForm.FromFile(filename);

            for (int idx = 0; idx < form.PageCount; idx += 2)
            {
                // Add a new page to the output document
                PdfPage page = outputDocument.AddPage();
                page.Orientation = PageOrientation.Landscape;
                double width  = page.Width;
                double height = page.Height;

                int rotate = page.Elements.GetInteger("/Rotate");

                gfx = XGraphics.FromPdfPage(page);

                // Set page number (which is one-based)
                form.PageNumber = idx + 1;

                box = new XRect(0, 0, width / 2, height);
                // Draw the page identified by the page number like an image
                gfx.DrawImage(form, box);

                // Write document file name and page number on each page
                box.Inflate(0, -10);
                gfx.DrawString(String.Format("- {1} -", filename, idx + 1),
                               font, XBrushes.Red, box, format);

                if (idx + 1 < form.PageCount)
                {
                    // Set page number (which is one-based)
                    form.PageNumber = idx + 2;

                    box = new XRect(width / 2, 0, width / 2, height);
                    // Draw the page identified by the page number like an image
                    gfx.DrawImage(form, box);

                    // Write document file name and page number on each page
                    box.Inflate(0, -10);
                    gfx.DrawString(String.Format("- {1} -", filename, idx + 2),
                                   font, XBrushes.Red, box, format);
                }
            }

            // Save the document...
            filename = "TwoPagesOnOne_tempfile.pdf";
            outputDocument.Save(filename);
            // ...and start a viewer.
            Process.Start(filename);
        }
 /// <summary>
 /// Draws the text.
 /// </summary>
 /// <param name="text">The text to be drawn.</param>
 /// <param name="font">The font.</param>
 /// <param name="brush">The text brush.</param>
 /// <param name="layoutRectangle">The layout rectangle.</param>
 public void DrawString(string text, XFont font, XBrush brush, XRect layoutRectangle)
 {
     DrawString(text, font, brush, layoutRectangle, XStringFormats.TopLeft);
 }
Beispiel #34
0
        public void Draw(XGraphics gfx, object param)
        {
            TransformsProvider tp = new TransformsProvider(gfx);
            XFont       font      = new XFont(this.FontFamilyName, this.FontSize, this.FontStyle);
            XSolidBrush brush     = new XSolidBrush(XColor.FromName(this.FontColorName));
            string      s         = string.Empty;

            if (param is DBNull)
            {
                s = string.Format("{0} {1} {2}", this._prefix, string.Empty, this._subfix);
            }
            if (param is string)
            {
                switch (_bindPropertyFormat)
                {
                case ValueParsingOption.None:
                    s = string.Format("{0} {1} {2}", this._prefix, param, this._subfix).Trim();
                    break;

                case ValueParsingOption.ParseInteger:
                    int intVal;
                    if (int.TryParse((string)param, out intVal))
                    {
                        s = string.Format("{0} {1} {2}", this._prefix, intVal.ToString("#,###"), this._subfix).Trim();
                    }
                    else
                    {
                        s = string.Format("{0} {1} {2}", this._prefix, param, this._subfix).Trim();
                    }
                    break;

                case ValueParsingOption.ParseFloat:
                    double      floatVal;
                    CultureInfo culture = null;
                    try
                    {
                        culture = CultureInfo.GetCultureInfo(this._bindPropertyCultureName);
                    }
                    catch
                    {
                        //Do nothing
                    }
                    if (culture == null)
                    {
                        s = string.Format("{0} {1} {2}", this._prefix, param, this._subfix).Trim();
                    }
                    else
                    {
                        if (double.TryParse((string)param, NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, culture, out floatVal))
                        {
                            s = string.Format("{0} {1} {2}", this._prefix, floatVal.ToString("#,###.##"), this._subfix).Trim();
                        }
                        else
                        {
                            s = string.Format("{0} {1} {2}", this._prefix, param, this._subfix).Trim();
                        }
                    }
                    break;
                }
            }
            if (param is int)
            {
                int intVal = (int)param;
                s = string.Format("{0} {1} {2}", this._prefix, (intVal).ToString("#,###"), this._subfix).Trim();
            }
            if ((param is double) || (param is float))
            {
                double floatVal = (double)param;
                s = string.Format("{0} {1} {2}", this._prefix, floatVal.ToString("#,###.##"), this._subfix).Trim();
            }

            if (base.Rect == XRect.Empty)
            {
                double x = tp.CmsToPts(this.X);
                double y = tp.CmsToPts(this.Y);
                gfx.DrawString(s, font, brush, x, y, XStringFormat.TopLeft);
            }
            else
            {
                XRect rect = tp.FromCmsToPts(base.Rect);
                gfx.DrawString(s, font, brush, rect, base.Format);
            }
        }
Beispiel #35
0
        // ----- DrawEllipse --------------------------------------------------------------------------

        public void DrawEllipse(XPen pen, XBrush brush, double x, double y, double width, double height)
        {
            Realize(pen, brush);

            // Useful information is here http://home.t-online.de/home/Robert.Rossmair/ellipse.htm (note: link was dead on November 2, 2015)
            // or here http://www.whizkidtech.redprince.net/bezier/circle/
            // Deeper but more difficult: http://www.tinaja.com/cubic01.asp
            XRect rect = new XRect(x, y, width, height);
            double δx = rect.Width / 2;
            double δy = rect.Height / 2;
            double fx = δx * Const.κ;
            double fy = δy * Const.κ;
            double x0 = rect.X + δx;
            double y0 = rect.Y + δy;

            // Approximate an ellipse by drawing four cubic splines.
            const string format = Config.SignificantFigures4;
            AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", x0 + δx, y0);
            AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
              x0 + δx, y0 + fy, x0 + fx, y0 + δy, x0, y0 + δy);
            AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
              x0 - fx, y0 + δy, x0 - δx, y0 + fy, x0 - δx, y0);
            AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
              x0 - δx, y0 - fy, x0 - fx, y0 - δy, x0, y0 - δy);
            AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
              x0 + fx, y0 - δy, x0 + δx, y0 - fy, x0 + δx, y0);
            AppendStrokeFill(pen, brush, XFillMode.Winding, true);
        }
Beispiel #36
0
        /// <summary>
        /// Resembles the DrawString function of GDI+.
        /// </summary>
        public void DrawString(XGraphics gfx, string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format)
        {
            double x = layoutRectangle.X;
            double y = layoutRectangle.Y;

            double lineSpace = font.GetHeight(); //old: font.GetHeight(gfx);
            double cyAscent = lineSpace * font.CellAscent / font.CellSpace;
            double cyDescent = lineSpace * font.CellDescent / font.CellSpace;

            bool bold = (font.Style & XFontStyle.Bold) != 0;
            bool italic = (font.Style & XFontStyle.Italic) != 0;
            bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
            bool underline = (font.Style & XFontStyle.Underline) != 0;

            //Debug.Assert(font.GlyphTypeface != null);
            TextBlock textBlock = new TextBlock(); //FontHelper.CreateTextBlock(text, font.GlyphTypeface, font.Size, brush.RealizeWpfBrush());
            if (layoutRectangle.Width > 0)
                textBlock.Width = layoutRectangle.Width;

            switch (format.Alignment)
            {
                case XStringAlignment.Near:
                    textBlock.TextAlignment = TextAlignment.Left;
                    break;

                case XStringAlignment.Center:
                    textBlock.TextAlignment = TextAlignment.Center;
                    break;

                case XStringAlignment.Far:
                    textBlock.TextAlignment = TextAlignment.Right;
                    break;
            }

            if (gfx.PageDirection == XPageDirection.Downwards)
            {
                switch (format.LineAlignment)
                {
                    case XLineAlignment.Near:
                        //y += cyAscent;
                        break;

                    case XLineAlignment.Center:
                        // TODO use CapHeight. PDFlib also uses 3/4 of ascent
                        y += (layoutRectangle.Height - textBlock.ActualHeight) / 2;
                        //y += -formattedText.Baseline + (font.Size * font.Metrics.CapHeight / font.unitsPerEm / 2) + layoutRectangle.Height / 2;
                        break;

                    case XLineAlignment.Far:
                        y += layoutRectangle.Height - textBlock.ActualHeight;
                        //y -= textBlock.ActualHeight;  //-formattedText.Baseline - cyDescent + layoutRectangle.Height;
                        break;

                    case XLineAlignment.BaseLine:
//#if !WINDOWS_PHONE
                        y -= textBlock.BaselineOffset;
//#else
//                        // No BaselineOffset in Silverlight WP yet.
//                        //y -= textBlock.BaselineOffset;
//#endif
                        break;
                }
            }
            else
            {
                throw new NotImplementedException("XPageDirection.Downwards");
            }

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

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

            if (underline)
                textBlock.TextDecorations = TextDecorations.Underline;

            // No strikethrough in Silverlight
            //if (strikeout)
            //{
            //  formattedText.SetTextDecorations(TextDecorations.Strikethrough);
            //  //double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace;
            //  //double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace;
            //  //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
            //}

            Canvas.SetLeft(textBlock, x);
            Canvas.SetTop(textBlock, y);
            ActiveCanvas.Children.Add(textBlock);
        }
Beispiel #37
0
        // TODO: incomplete - srcRect not used
        public void DrawImage(XImage image, XRect destRect, XRect srcRect, XGraphicsUnit srcUnit)
        {
            const string format = Config.SignificantFigures4;

            double x = destRect.X;
            double y = destRect.Y;
            double width = destRect.Width;
            double height = destRect.Height;

            string name = Realize(image);
            if (!(image is XForm))
            {
                if (_gfx.PageDirection == XPageDirection.Downwards)
                {
                    AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do\nQ\n",
                        x, y + height, width, height, name);
                }
                else
                {
                    AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
                        x, y, width, height, name);
                }
            }
            else
            {
                BeginPage();

                XForm form = (XForm)image;
                form.Finish();

                PdfFormXObject pdfForm = Owner.FormTable.GetForm(form);

                double cx = width / image.PointWidth;
                double cy = height / image.PointHeight;

                if (cx != 0 && cy != 0)
                {
                    XPdfForm xForm = image as XPdfForm;
                    if (_gfx.PageDirection == XPageDirection.Downwards)
                    {
                        double xDraw = x;
                        double yDraw = y;
                        if (xForm != null)
                        {
                            // Yes, it is an XPdfForm - adjust the position where the page will be drawn.
                            xDraw -= xForm.Page.MediaBox.X1;
                            yDraw += xForm.Page.MediaBox.Y1;
                        }
                        AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
                            xDraw, yDraw + height, cx, cy, name);
                    }
                    else
                    {
                        // TODO Translation for MediaBox.
                        AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
                            x, y, cx, cy, name);
                    }
                }
            }
        }
Beispiel #38
0
        public static void CreateAssemblyDocument(Assembly.Assembly assembly, IatRunConfiguration config, string filename)
        {
            // Create the bounding rectangles for each layer
            // add them up to a single rectangle (bounding rectangle for all layers)
            // to find out how much we have to move each component/gerber shape so it is aligned with 0/0
            var boundingRects = assembly.AllLayers.Select(d => d.FindExtents()).ToList();


            float moveLeft = boundingRects.Min(d => d.Left);
            float moveTop  = boundingRects.Min(d => d.Top);

            // For each shape, move it to the according positions
            // Calculate the extents again (the result must be no item to the left/top of 0/0)
            var finalRects = new List <RectangleF>();

            foreach (var lgs in assembly.AllLayers)
            {
                lgs.PerformRelocation(moveLeft, moveTop);
                finalRects.Add(lgs.FindExtents());
            }

            float rFinalMinX = finalRects.Min(d => d.Left);
            float rFinalMinY = finalRects.Min(d => d.Top);

            Debug.Assert(Math.Abs(rFinalMinX) < 0.1);
            Debug.Assert(Math.Abs(rFinalMinY) < 0.1);

            // Since the minimum values are both 0.0 now, calculate the max values
            float maxExtensionX = finalRects.Max(d => d.Left + d.Width);
            float maxExtensionY = finalRects.Max(d => d.Top + d.Height);

            // We also need to move the components with the same factor
            foreach (Component c in assembly.ComponentsTop.Values.SelectMany(d => d))
            {
                c.PositionX -= (decimal)moveLeft;
                c.PositionY -= (decimal)moveTop;
            }
            foreach (Component c in assembly.ComponentsBottom.Values.SelectMany(d => d))
            {
                c.PositionX -= (decimal)moveLeft;
                c.PositionY -= (decimal)moveTop;
            }
            // ReSharper disable once UnusedVariable
            foreach (PointF pf in assembly.DnpPositions)
            {
                // TODO
                //pf.X -= (decimal) moveLeft;
            }

            // Setup the required variables
            // Get the amount of lines and colors (currently tested for 5 only)
            int nrLines = config.OutputSettings.ComponentColors.Count;

            List <XColor> colorsFromConfiguration = new List <XColor>();

            for (int i = 0; i < nrLines; i++)
            {
                colorsFromConfiguration.Add(GetXColorFromColor(config.OutputSettings.ComponentColors[i]));
            }

            // Create a temporary PDF file

            PdfDocument pdfDocument = new PdfDocument();

            pdfDocument.Info.Title    = "Intelligent Assembly Tool";
            pdfDocument.Info.Author   = "";
            pdfDocument.Info.Subject  = "Intelligent Assembly Tool";
            pdfDocument.Info.Keywords = "IAT";


            List <Dictionary <string, List <Component> > > componentsGroupTop    = SplitAssembly(assembly.ComponentsTop, config);
            List <Dictionary <string, List <Component> > > componentsGroupBottom = SplitAssembly(assembly.ComponentsBottom, config);

            Dictionary <ComponentLayer, List <Dictionary <string, List <Component> > > > allLayerData =
                new Dictionary <ComponentLayer, List <Dictionary <string, List <Component> > > >
            {
                { ComponentLayer.Top, componentsGroupTop },
                { ComponentLayer.Bottom, componentsGroupBottom }
            };

            foreach (var componentGroups in allLayerData)
            {
                foreach (var componentGroup in componentGroups.Value)
                {
                    PdfPage page = pdfDocument.AddPage();

                    page.Size = PageSize.A4;
                    XGraphics gfx = XGraphics.FromPdfPage(page);

                    // Draw the text string at the very bottom
                    XFont          infoFont          = new XFont("Consolas", 6, XFontStyle.Regular);
                    XTextFormatter infoTextFormatter = new XTextFormatter(gfx)
                    {
                        Alignment = XParagraphAlignment.Center
                    };
                    XRect infoRect = new XRect(0, page.Height - 20, page.Width, 20);

                    var versionNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    infoTextFormatter.DrawString("Intelligent Assembly Tool " + versionNumber + Environment.NewLine + "Created by Thomas Linder / [email protected] / http://www.thomaslinder.at/iat", infoFont, XBrushes.Black, infoRect);

                    // Draw the component box at the bottom
                    XPen tableDrawPen = new XPen(XColors.Black)
                    {
                        Width    = 0.01,
                        LineCap  = XLineCap.Round,
                        LineJoin = XLineJoin.Round
                    };

                    XFont          tableFont          = new XFont("Consolas", 8, XFontStyle.Regular);
                    XTextFormatter tableTextFormatter = new XTextFormatter(gfx);

                    // General page/table layout
                    double lineHeight         = 12.0;
                    double topOffsetTotal     = page.Height * 0.95 - nrLines * lineHeight;
                    double lineStartX         = page.Width * 0.05;
                    double lineEndX           = page.Width * 0.95;
                    double rectangleExtension = lineHeight - 4;

                    // Calculate column length for amount, article number & description
                    double remainingLineLength           = lineEndX - lineStartX - lineHeight;
                    double lengthAmountField             = remainingLineLength * 0.05;
                    double lengthArticleNumberField      = remainingLineLength * 0.25;
                    double lengthArticleDescriptionField = remainingLineLength * 0.7;

                    double bottomOffsetTotal = topOffsetTotal + nrLines * lineHeight;

                    // Top Line
                    gfx.DrawLine(tableDrawPen, lineStartX, topOffsetTotal, lineEndX, topOffsetTotal);
                    // Bottom Line
                    gfx.DrawLine(tableDrawPen, lineStartX, topOffsetTotal + (nrLines) * lineHeight, lineEndX, topOffsetTotal + (nrLines) * lineHeight);
                    // Left Vertical
                    gfx.DrawLine(tableDrawPen, lineStartX, topOffsetTotal, lineStartX, bottomOffsetTotal);
                    // Right Vertical
                    gfx.DrawLine(tableDrawPen, lineEndX, topOffsetTotal, lineEndX, bottomOffsetTotal);
                    // First column (color rectangle)
                    gfx.DrawLine(tableDrawPen, lineStartX + lineHeight, topOffsetTotal, lineStartX + lineHeight, bottomOffsetTotal);
                    // Second column (amount)
                    double amountEndX = lineStartX + lineHeight + lengthAmountField;
                    gfx.DrawLine(tableDrawPen, amountEndX, topOffsetTotal, amountEndX, bottomOffsetTotal);
                    // Third column (article number)
                    double articleNumberEndX = lineStartX + lineHeight + lengthAmountField + lengthArticleNumberField;
                    gfx.DrawLine(tableDrawPen, articleNumberEndX, topOffsetTotal, articleNumberEndX, bottomOffsetTotal);



                    for (int lineIndex = 0; lineIndex < Math.Min(nrLines, componentGroup.Count); lineIndex++)
                    {
                        gfx.DrawRectangle(new XSolidBrush(colorsFromConfiguration[lineIndex]), lineStartX + 2, topOffsetTotal + lineIndex * lineHeight + 2, rectangleExtension, rectangleExtension);
                        XRect amountRect = new XRect(lineStartX + lineHeight, topOffsetTotal + lineIndex * lineHeight, lengthAmountField, lineHeight);
                        tableTextFormatter.DrawString(componentGroup.ElementAt(lineIndex).Value.Count.ToString(), tableFont, XBrushes.Black, amountRect, XStringFormats.TopLeft);
                        XRect articleNumberRect = new XRect(lineStartX + lineHeight + lengthAmountField, topOffsetTotal + lineIndex * lineHeight, lengthArticleNumberField, lineHeight);
                        tableTextFormatter.DrawString(componentGroup.ElementAt(lineIndex).Value[0].LibRef, tableFont, XBrushes.Black, articleNumberRect, XStringFormats.TopLeft);
                        XRect articleDescriptionRect = new XRect(lineStartX + lineHeight + lengthAmountField + lengthArticleNumberField, topOffsetTotal + lineIndex * lineHeight, lengthArticleDescriptionField, lineHeight);
                        tableTextFormatter.DrawString(componentGroup.ElementAt(lineIndex).Value[0].Description, tableFont, XBrushes.Black, articleDescriptionRect, XStringFormats.TopLeft);

                        gfx.DrawLine(tableDrawPen, lineStartX, topOffsetTotal + (lineIndex + 1) * lineHeight, lineEndX, topOffsetTotal + (lineIndex + 1) * lineHeight);
                    }


                    // Get the page size to calculate the available space
                    double availableSizeX = page.Width * 0.9;                                          // 90 % of the page width
                    double availableSizeY = page.Height * 0.85 - (bottomOffsetTotal - topOffsetTotal); // Leave 5% of space on top and bottom and between the table and the drawing

                    double scaleFactorX = availableSizeX / maxExtensionX;
                    double scaleFactorY = availableSizeY / maxExtensionY;

                    double scaleFactor = Math.Min(scaleFactorX, scaleFactorY);

                    if (componentGroups.Key == ComponentLayer.Top)
                    {
                        DrawLayers(gfx, config, ComponentLayer.Top, scaleFactor, assembly.TopOverlayLayer, assembly.TopPasteLayer, assembly.MechanicalOutlineLayer, maxExtensionX, maxExtensionY, componentGroup, colorsFromConfiguration);
                    }
                    else
                    {
                        DrawLayers(gfx, config, ComponentLayer.Bottom, scaleFactor, assembly.BottomOverlayLayer, assembly.BottomPasteLayer, assembly.MechanicalOutlineLayer, maxExtensionX, maxExtensionY, componentGroup, colorsFromConfiguration);
                    }
                }
            }


            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            pdfDocument.Save(filename);
        }
Beispiel #39
0
 internal static void TransformRect(ref XRect rect, ref XMatrix matrix)
 {
     if (!rect.IsEmpty)
     {
         XMatrixTypes type = matrix._type;
         if (type != XMatrixTypes.Identity)
         {
             if ((type & XMatrixTypes.Scaling) != XMatrixTypes.Identity)
             {
                 rect.X *= matrix._m11;
                 rect.Y *= matrix._m22;
                 rect.Width *= matrix._m11;
                 rect.Height *= matrix._m22;
                 if (rect.Width < 0)
                 {
                     rect.X += rect.Width;
                     rect.Width = -rect.Width;
                 }
                 if (rect.Height < 0)
                 {
                     rect.Y += rect.Height;
                     rect.Height = -rect.Height;
                 }
             }
             if ((type & XMatrixTypes.Translation) != XMatrixTypes.Identity)
             {
                 rect.X += matrix._offsetX;
                 rect.Y += matrix._offsetY;
             }
             if (type == XMatrixTypes.Unknown)
             {
                 XPoint point1 = matrix.Transform(rect.TopLeft);
                 XPoint point2 = matrix.Transform(rect.TopRight);
                 XPoint point3 = matrix.Transform(rect.BottomRight);
                 XPoint point4 = matrix.Transform(rect.BottomLeft);
                 rect.X = Math.Min(Math.Min(point1.X, point2.X), Math.Min(point3.X, point4.X));
                 rect.Y = Math.Min(Math.Min(point1.Y, point2.Y), Math.Min(point3.Y, point4.Y));
                 rect.Width = Math.Max(Math.Max(point1.X, point2.X), Math.Max(point3.X, point4.X)) - rect.X;
                 rect.Height = Math.Max(Math.Max(point1.Y, point2.Y), Math.Max(point3.Y, point4.Y)) - rect.Y;
             }
         }
     }
 }
        public FileResult GerarRelatorio(int?id)
        {
            using (var doc = new PdfSharpCore.Pdf.PdfDocument()) {
                var page = doc.AddPage();
                page.Size        = PdfSharpCore.PageSize.A4;
                page.Orientation = PdfSharpCore.PageOrientation.Portrait;

                var grafics          = XGraphics.FromPdfPage(page);
                var corFonte         = XBrushes.Black;
                var textFormatter    = new XTextFormatter(grafics);
                var textJustify      = new XTextFormatter(grafics);
                var fonteOrganizacao = new XFont("Times New Roman", 12);
                var fonteTitulo      = new XFont("Times New Roman", 12, XFontStyle.Bold);
                var fonteDesc        = new XFont("Times New Roman", 8, XFontStyle.Bold);
                var titulo           = new XFont("Times New Roman", 10, XFontStyle.Bold);
                var fonteDetalhes    = new XFont("Times New Roman", 7);
                var fonteNegrito     = new XFont("Times New Roman", 12, XFontStyle.Bold);
                var logo             = @"C:\Logo.png";
                var qtdpaginas       = doc.PageCount;


                textFormatter.DrawString(qtdpaginas.ToString(), new XFont("Arial", 7), corFonte,
                                         new XRect(575, 825, page.Width, page.Height));

                List <CitacaoCarta> dados = new List <CitacaoCarta>();

                MySqlConnection con = new MySqlConnection();
                con.ConnectionString = c.ConexaoDados();
                con.Open();
                string          data    = DateTime.Now.ToShortDateString();
                MySqlCommand    command = new MySqlCommand("SELECT * FROM citacaocarta  WHERE  Id = '" + id + "'", con);
                MySqlDataReader reader  = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        dados.Add(new CitacaoCarta()
                        {
                            Autos    = reader.GetString("Autos"),
                            Contrato = reader.GetInt64("Contrato"),
                            Vara     = reader.GetString("Vara"),
                            Comarca  = reader.GetString("Comarca"),
                            Estado   = reader.GetString("Estado"),
                            Banco    = reader.GetString("Banco"),
                            Reu      = reader.GetString("Reu"),
                            Endereco = reader.GetString("Endereco"),
                            Oab      = reader.GetString("Oab"),
                            Data     = reader.GetString("Data")
                        });;
                    }
                    Console.WriteLine(data);
                }

                for (int i = 0; i < dados.Count; i++)
                {
                    //Imagem todo da pagina
                    XImage imagem = XImage.FromFile(logo);
                    grafics.DrawImage(imagem, 200, 40, 200, 80);

                    var topo =
                        "EXCELENTÍSSIMO SENHOR DOUTOR JUIZ DE DIREITO DA " + dados[i].Vara + " DA " + dados[i].Comarca + " – ESTADO DO " + dados[i].Estado;

                    var dadosAutos =
                        "Autos nº: " + dados[i].Autos + "\n" +
                        "Contrato nº: " + dados[i].Contrato;


                    var texto =
                        "                                 " + dados[i].Banco + ", já qualificada(o) nos autos em epígrafe, " +
                        "que move em face de " + dados[i].Reu + ", também já qualificada(o), por seus advogados que esta subscrevem, vem, " +
                        "respeitosamente perante Vossa Excelência, REQUERER com fundamento nos Art. 246, I do CPC, que a citação seja realizada " +
                        "através de correio com aviso de recebimento, direcionado ao seguinte " +
                        "endereço: " + dados[i].Endereco + "\n \n \n" +
                        "                              Outrossim, requer que todas as intimações dos atos processuais " +
                        "sejam efetivadas forma prevista nos artigos 236 e 237 do C.P.C., na pessoa de Cristiane Belinati Garcia Lopes, "
                        + dados[i].Oab + " independentemente dos demais procuradores constantes nas procurações e substabelecimentos juntados a estes autos, " +
                        "sob pena de nulidade da intimação, conforme previsto no artigo 247 do C.P.C.\n \n \n" +
                        "                                 Termos em que,\n" +
                        "                                 Pede deferimento.\n" +
                        "                                 Maringá / PR, " + dados[i].Data;


                    var oab =
                        "CRISTIANE BELINATI GARCIA LOPES\n" +
                        dados[i].Oab;

                    var enderecoRodape =
                        "Endereço: Rua João Paulino Vieira Filho, 625, 12º andar – Sala 1201\n" +
                        "Bairro: Zona 01 CEP: 87020-015 - Fone: (44) 3033-9291 / (44) 2103-9291\n" +
                        "Maringa/PR";

                    //Texto do Topo
                    textJustify.Alignment = XParagraphAlignment.Left;
                    XRect rectTopo = new XRect(50, 155, 490, page.Height);
                    textJustify.DrawString(topo, fonteTitulo, corFonte, rectTopo, XStringFormats.TopLeft);

                    //Dados do Contrato
                    textJustify.Alignment = XParagraphAlignment.Left;
                    XRect rectDados = new XRect(50, 230, 490, page.Height);
                    textJustify.DrawString(dadosAutos, fonteNegrito, corFonte, rectDados, XStringFormats.TopLeft);

                    //Dados do Texto
                    textJustify.Alignment = XParagraphAlignment.Justify;
                    XRect rectTexto = new XRect(50, 290, 490, page.Height);
                    textJustify.DrawString(texto, fonteOrganizacao, corFonte, rectTexto, XStringFormats.TopLeft);

                    //Texto OAB
                    textJustify.Alignment = XParagraphAlignment.Center;
                    XRect rectOab = new XRect(50, 625, 490, page.Height);
                    textJustify.DrawString(oab, fonteTitulo, corFonte, rectOab, XStringFormats.TopLeft);

                    textJustify.Alignment = XParagraphAlignment.Center;
                    XRect rectenderecoRodape = new XRect(50, 790, 490, page.Height);
                    textJustify.DrawString(enderecoRodape, fonteDetalhes, corFonte, rectenderecoRodape, XStringFormats.TopLeft);
                }

                using (MemoryStream stream = new MemoryStream()) {
                    var contentType = "application/pdf";
                    doc.Save(stream, false);
                    var nomeArquivo = "Carta de Citação.pdf";
                    return(File(stream.ToArray(), contentType, nomeArquivo));
                }
            }
        }
    // ----- DrawEllipse --------------------------------------------------------------------------

    public void DrawEllipse(XPen pen, XBrush brush, double x, double y, double width, double height)
    {
      Realize(pen, brush);

      // Useful information are here http://home.t-online.de/home/Robert.Rossmair/ellipse.htm
      // or here http://www.whizkidtech.redprince.net/bezier/circle/
      // Deeper but more difficult: http://www.tinaja.com/cubic01.asp
      // Petzold: 4/3 * tan(α / 4)
      const double κ = 0.5522847498;  // := 4/3 * (1 - cos(-π/4)) / sin(π/4)) <=> 4/3 * sqrt(2) - 1
      XRect rect = new XRect(x, y, width, height);
      double δx = rect.Width / 2;
      double δy = rect.Height / 2;
      double fx = δx * κ;
      double fy = δy * κ;
      double x0 = rect.X + δx;
      double y0 = rect.Y + δy;

      AppendFormat("{0:0.####} {1:0.####} m\n", x0 + δx, y0);
      AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
        x0 + δx, y0 + fy, x0 + fx, y0 + δy, x0, y0 + δy);
      AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
        x0 - fx, y0 + δy, x0 - δx, y0 + fy, x0 - δx, y0);
      AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
        x0 - δx, y0 - fy, x0 - fx, y0 - δy, x0, y0 - δy);
      AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
        x0 + fx, y0 - δy, x0 + δx, y0 - fy, x0 + δx, y0);
      AppendStrokeFill(pen, brush, XFillMode.Winding, true);
    }
Beispiel #42
0
        // create a preview
        public void CreatePreview()
        {
            XRect rect;
            XPen  pen;

            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();

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

            // Create an empty page
            PdfSharp.Pdf.PdfPage page = document.AddPage();

            // Get an XGraphics object for drawing
            page.Size        = PageSize.A5;
            page.Orientation = PageOrientation.Landscape;
            XGraphics gfx = XGraphics.FromPdfPage(page);
            double    x = 50, y = 100;
            XFont     fontH1 = new XFont("Times", 18, XFontStyle.Bold);

            XFont font = new XFont("Times", 12);

            XFont fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);

            double ls = font.GetHeight(gfx);

            // 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

            pen = new XPen(XColors.Red, 4);

            pen.DashStyle = XDashStyle.Dash;

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

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

            gfx.TranslateTransform(x + 140, y + 30);

            for (int idx = 0; idx < 360; idx += 10)

            {
                gfx.RotateTransform(10);

                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }

            gfx.Restore(gs);

            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen  = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor(KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush 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;
            XGraphicsState state   = gfx.Save();
            XRect          rcImage = new XRect(100, y, 100, 100 * Math.Sqrt(2));

            gfx.DrawRectangle(XBrushes.Snow, rcImage);
            string kara = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Printex");

            gfx.DrawImage(XPdfForm.FromFile(System.IO.Path.Combine(kara, "slother.pdf")), rcImage);
            gfx.Restore(state);
        }
    // TODO: incomplete - srcRect not used
    public void DrawImage(XImage image, XRect destRect, XRect srcRect, XGraphicsUnit srcUnit)
    {
      double x = destRect.X;
      double y = destRect.Y;
      double width = destRect.Width;
      double height = destRect.Height;

      string name = Realize(image);
      if (!(image is XForm))
      {
        if (this.gfx.PageDirection == XPageDirection.Downwards)
        {
          AppendFormat("q {2:0.####} 0 0 -{3:0.####} {0:0.####} {4:0.####} cm {5} Do\nQ\n",
            x, y, width, height, y + height, name);
        }
        else
        {
          AppendFormat("q {2:0.####} 0 0 {3:0.####} {0:0.####} {1:0.####} cm {4} Do Q\n",
            x, y, width, height, name);
        }
      }
      else
      {
        BeginPage();

        XForm xForm = (XForm)image;
        xForm.Finish();

        PdfFormXObject pdfForm = Owner.FormTable.GetForm(xForm);

        double cx = width / image.PointWidth;
        double cy = height / image.PointHeight;

        if (cx != 0 && cy != 0)
        {
          if (this.gfx.PageDirection == XPageDirection.Downwards)
          {
            AppendFormat("q {2:0.####} 0 0 -{3:0.####} {0:0.####} {4:0.####} cm 100 Tz {5} Do Q\n",
              x, y, cx, cy, y + height, name);
          }
          else
          {
            AppendFormat("q {2:0.####} 0 0 {3:0.####} {0:0.####} {1:0.####} cm {4} Do Q\n",
              x, y, cx, cy, name);
          }
        }
      }
    }
        internal static void Export(Library library, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            List <PDFDocumentExportItem> pdf_document_export_items_values = new List <PDFDocumentExportItem>(pdf_document_export_items.Values);

            for (int i = 0; i < pdf_document_export_items_values.Count; ++i)
            {
                var item = pdf_document_export_items_values[i];
                try
                {
                    StatusManager.Instance.UpdateStatus("ContentExport", String.Format("Exporting entry {0} of {1}", i, pdf_document_export_items_values.Count), i, pdf_document_export_items_values.Count);

                    using (PdfDocument document = PdfReader.Open(item.filename, PdfDocumentOpenMode.Modify))
                    {
                        // First the properties
                        document.Info.Title            = item.pdf_document.TitleCombined;
                        document.Info.Author           = item.pdf_document.AuthorsCombined;
                        document.Info.ModificationDate = DateTime.Now;
                        document.Info.Creator          = "Qiqqa.com library export v1";
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (string tag in TagTools.ConvertTagBundleToTags(item.pdf_document.Tags))
                            {
                                sb.Append(tag);
                                sb.Append(";");
                            }
                            document.Info.Keywords = sb.ToString();
                        }

                        // Then the main comments (if any)
                        {
                            string comments = item.pdf_document.Comments;
                            if (!String.IsNullOrEmpty(comments))
                            {
                                PdfPage page = document.Pages[0];

                                using (XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend))
                                {
                                    XRect             rect           = new XRect(5, 5, 100, 100);
                                    PdfTextAnnotation new_annotation = new PdfTextAnnotation();
                                    new_annotation.Contents  = comments;
                                    new_annotation.Icon      = PdfTextAnnotationIcon.Note;
                                    new_annotation.Rectangle = new PdfRectangle(gfx.Transformer.WorldToDefaultPage(rect));
                                    page.Annotations.Add(new_annotation);
                                }
                            }
                        }

                        // Then the highlights
                        foreach (PDFHighlight highlight in item.pdf_document.Highlights.GetAllHighlights())
                        {
                            PdfPage page = document.Pages[highlight.Page - 1];
                            using (XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend))
                            {
                                XColor color = XColor.FromArgb(StandardHighlightColours.GetColor(highlight.Color));
                                XPen   pen   = new XPen(color);
                                XBrush brush = new XSolidBrush(color);
                                XRect  rect  = new XRect(highlight.Left * gfx.PageSize.Width, highlight.Top * gfx.PageSize.Height, highlight.Width * gfx.PageSize.Width, highlight.Height * gfx.PageSize.Height);
                                gfx.DrawRectangle(brush, rect);
                            }
                        }

                        // Then the annotations
                        foreach (PDFAnnotation annotation in item.pdf_document.Annotations)
                        {
                            if (annotation.Deleted)
                            {
                                continue;
                            }

                            PdfPage page = document.Pages[annotation.Page - 1];
                            using (XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend))
                            {
                                XColor color = XColor.FromArgb(annotation.Color);
                                XPen   pen   = new XPen(color);
                                XBrush brush = new XSolidBrush(color);
                                XRect  rect  = new XRect(annotation.Left * gfx.PageSize.Width, annotation.Top * gfx.PageSize.Height, annotation.Width * gfx.PageSize.Width, annotation.Height * gfx.PageSize.Height);
                                gfx.DrawRectangle(brush, rect);

                                PdfTextAnnotation new_annotation = new PdfTextAnnotation();
                                new_annotation.Contents  = String.Format("Tags:{0}\n{1}", annotation.Tags, annotation.Text);
                                new_annotation.Icon      = PdfTextAnnotationIcon.Note;
                                new_annotation.Color     = color;
                                new_annotation.Opacity   = 0.5;
                                new_annotation.Open      = false;
                                new_annotation.Rectangle = new PdfRectangle(gfx.Transformer.WorldToDefaultPage(rect));
                                page.Annotations.Add(new_annotation);

                                //foreach (var pair in new_annotation.Elements)
                                //{
                                //    Logging.Debug("   {0}={1}", pair.Key, pair.Value);
                                //}
                            }
                        }

                        // Save it
                        Logging.Info("Saving {0}", item.filename);
                        document.Save(item.filename);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error updating PDF for " + item.filename);
                }

                StatusManager.Instance.UpdateStatus("ContentExport", String.Format("Exported your PDF content"));
            }
        }
Beispiel #45
0
 /// <summary>
 /// The render text.
 /// </summary>
 /// <param name="info">
 /// The info.
 /// </param>
 private void RenderText(BarCodeRenderInfo info)
 {
     if (info.Font == null)
         info.Font = new XFont("Courier New", this.Size.Height / 6);
     XPoint center = info.Position + CodeBase.CalcDistance(this.anchor, AnchorType.TopLeft, this.size);
     if (this.TextLocation == TextLocation.Above)
         info.Gfx.DrawString(this.text, info.Font, info.Brush, new XRect(center, this.Size), XStringFormats.TopCenter);
     else if (this.TextLocation == TextLocation.AboveEmbedded)
     {
         XSize textSize = info.Gfx.MeasureString(this.text, info.Font);
         textSize.Width += this.Size.Width * .15;
         XPoint point = info.Position;
         point.X += (this.Size.Width - textSize.Width) / 2;
         XRect rect = new XRect(point, textSize);
         info.Gfx.DrawRectangle(XBrushes.White, rect);
         info.Gfx.DrawString(this.text, info.Font, info.Brush, new XRect(center, this.Size), XStringFormats.TopCenter);
     }
     else if (this.TextLocation == TextLocation.Below)
         info.Gfx.DrawString(this.text, info.Font, info.Brush, new XRect(center, this.Size), XStringFormats.BottomCenter);
     else if (this.TextLocation == TextLocation.BelowEmbedded)
     {
         XSize textSize = info.Gfx.MeasureString(this.text, info.Font);
         textSize.Width += this.Size.Width * .15;
         XPoint point = info.Position;
         point.X += (this.Size.Width - textSize.Width) / 2;
         point.Y += this.Size.Height - textSize.height;
         XRect rect = new XRect(point, textSize);
         info.Gfx.DrawRectangle(XBrushes.White, rect);
         info.Gfx.DrawString(this.text, info.Font, info.Brush, new XRect(center, this.Size), XStringFormats.BottomCenter);
     }
 }
Beispiel #46
0
        private double PrintInvoiceRow(XGraphics printer, double startY, InvoiceLine invoiceRow, bool odd)
        {
            int topMargin = 5;
            int rowHeight = 15;

            XColor strokeColor = XColor.FromArgb(100, 100, 100);
            XPen   strokePen   = new XPen(strokeColor);

            XFont font = new XFont("Times", 10, XFontStyle.Regular);

            List <string> lines = new List <string>();

            string[] returnSplit = invoiceRow.Product.Name.Split("\n");

            List <string> breaks = returnSplit.ToList();

            foreach (string brr in breaks)
            {
                string        br = brr;
                StringBuilder sb = new StringBuilder();
                br = br.Replace("\n", " ");
                br = br.Replace("\r", " ");

                foreach (string s in br.Split(" "))
                {
                    XSize size = printer.MeasureString(sb.ToString() + s + " ", font);
                    if (size.Width > COL1_WIDTH - 10)
                    {
                        lines.Add(sb.ToString());
                        sb = new StringBuilder();
                        sb.Append("  ");
                    }
                    sb.Append(s).Append(" ");
                }

                if (sb.Length >= 1)
                {
                    lines.Add(sb.ToString());
                }
            }

            XRect r1 = new XRect(COL1_START_X, startY - 10, COL1_WIDTH, rowHeight * lines.Count + topMargin);
            XRect r2 = new XRect(COL2_START_X, startY - 10, COL2_WIDTH, rowHeight * lines.Count + topMargin);

            if (odd)
            {
                printer.DrawRectangles(strokePen, new XSolidBrush(XColor.FromArgb(230, 230, 230)), new XRect[] { r1, r2 });
            }
            else
            {
                printer.DrawRectangles(strokePen, new XRect[] { r1, r2 });
            }

            startY += topMargin;
            double yPos = startY; // + rowHeight - rowHeight * 2 / 5;

            foreach (string line in lines)
            {
                printer.DrawString(line, font, brush, new XPoint(COL1_START_X + 10, yPos));
                yPos += rowHeight;
            }

            startY += rowHeight * lines.Count;

            yPos = startY - rowHeight * lines.Count * 2 / 5 - 10;
            printer.DrawString(invoiceRow.getTotalstring(), font, brush, new XPoint(COL2_START_X + 10, yPos));

            return(startY);
        }
 public void SetAndRealizeClipRect(XRect clipRect)
 {
   XGraphicsPath clipPath = new XGraphicsPath();
   clipPath.AddRectangle(clipRect);
   RealizeClipPath(clipPath);
 }
Beispiel #48
0
 /// <summary>
 /// Draws the text.
 /// </summary>
 /// <param name="text">The text to be drawn.</param>
 /// <param name="font">The font.</param>
 /// <param name="brush">The text brush.</param>
 /// <param name="layoutRectangle">The layout rectangle.</param>
 public void DrawString(string text, XFont font, XBrush brush, XRect layoutRectangle)
 {
     DrawString(text, font, brush, layoutRectangle, XStringFormats.TopLeft);
 }