示例#1
0
        ////////////////////////////////////////////////////////////////////
        // Draw frame around example area
        ////////////////////////////////////////////////////////////////////

        private void DrawFrameAndBackgroundWaterMark()
        {
            // save graphics state
            Contents.SaveGraphicsState();

            // Draw frame around the page
            // Set line width to 0.02"
            Contents.SetLineWidth(0.02);

            // set frame color dark blue
            Contents.SetColorStroking(Color.DarkBlue);

            // use water mark tiling pattern to fill the frame
            Contents.SetPatternNonStroking(WaterMark);

            // rectangle position: x=1.0", y=1.0", width=6.5", height=9.0"
            Contents.DrawRectangle(1.0, 1.0, 6.5, 9.0, PaintOp.CloseFillStroke);

            // restore graphics sate
            Contents.RestoreGraphicsState();

            // draw article name under the frame
            // Note: the \u00a4 is character 164 that was substituted during Font resource definition
            // this character is a solid circle it is normally Unicode 9679 or \u25cf in the Arial family
            Contents.DrawText(ArialNormal, 9.0, 1.1, 0.85, "PdfFileWriter \u25cf PDF File Writer C# Class Library \u25cf Author: Uzi Granot");

            // draw web link to the article
            Contents.DrawWebLink(Page, ArialNormal, 9.0, 7.4, 0.85, TextJustify.Right, DrawStyle.Underline, Color.Blue, "Click to view article",
                                 "http://www.codeproject.com/Articles/570682/PDF-File-Writer-Csharp-Class-Library-Version");

            return;
        }
        public void OnePage
        (
            int Cols,
            int Rows
        )
        {
            // Add new page
            PdfPage Page = new PdfPage(Document);

            // Add contents to page
            PdfContents Contents = new PdfContents(Page);

            double Left   = CenterX - 0.5 * Cols;
            double Right  = CenterX + 0.5 * Cols;
            double Top    = CenterY + 0.5 * Rows;
            double Bottom = CenterY - 0.5 * Rows;

            Contents.DrawText(ArialFont, FontSize, CenterX, Top + Descent + 0.2, TextJustify.Center, Cols == Rows ? "Square" : "Rectangle");

            // save state
            Contents.SaveGraphicsState();

            Contents.SetLineWidth(0.1);
            Contents.SetColorStroking(Color.Black);
            Contents.SetColorNonStroking(Color.LightBlue);
            Contents.DrawRectangle(Left, Bottom, Cols, Rows, PaintOp.CloseFillStroke);
            Contents.RestoreGraphicsState();

            Contents.SaveGraphicsState();
            Contents.SetLineWidth(0.04);
            for (int Row = 0; Row <= Rows; Row++)
            {
                Contents.DrawLine(Left - 0.25, Bottom + Row, Right, Bottom + Row);
                Contents.DrawText(ArialFont, FontSize, Left - 0.35, Bottom + Row - Descent, TextJustify.Right, Row.ToString());
            }

            for (int Col = 0; Col <= Cols; Col++)
            {
                Contents.DrawLine(Left + Col, Bottom - 0.25, Left + Col, Top);
                Contents.DrawText(ArialFont, FontSize, Left + Col, Bottom - 0.25 - FontHeight, TextJustify.Center, Col.ToString());
            }

            for (int Index = 0; Index < Rows * Cols; Index++)
            {
                int Row = Index / Cols;
                int Col = Index % Cols;
                Contents.DrawText(ArialFont, FontSize, Left + 0.5 + Col, Top - 0.5 - Descent - Row, TextJustify.Center, (Index + 1).ToString());
            }

            Contents.DrawText(ArialFont, FontSize, CenterX, Bottom - 1.0, TextJustify.Center, "Area");
            Contents.DrawText(ArialFont, FontSize, CenterX, Bottom - 1.4, TextJustify.Center, string.Format("{0} X {1} = {2}", Rows, Cols, Rows * Cols));

            // restore graphics state
            Contents.RestoreGraphicsState();
            return;
        }
        ////////////////////////////////////////////////////////////////////
        // Draw rectangle with rounded corners and filled with brick pattern
        ////////////////////////////////////////////////////////////////////

        private void DrawBrickPattern
        (
            PdfDocument Document,
            PdfContents Contents
        )
        {
            // Define brick tilling pattern resource
            // Arguments: PdfDocument class, Scale factor (0.25), Stroking color (lines between bricks), Nonstroking color (brick)
            // Return value: tilling pattern resource
            PdfTilingPattern BrickPattern = PdfTilingPattern.SetBrickPattern(Document, 0.25, Color.LightYellow, Color.SandyBrown);

            // save graphics state
            Contents.SaveGraphicsState();

            // set outline width 0.04"
            Contents.SetLineWidth(0.04);

            // set outline color to purple
            Contents.SetColorStroking(Color.Purple);

            // set fill pattern to brick
            Contents.SetPatternNonStroking(BrickPattern);

            // draw rounded rectangle filled with brick pattern
            Contents.DrawRoundedRectangle(1.13, 5.0, 1.4, 1.4, 0.2, PaintOp.CloseFillStroke);

            // restore graphics sate
            Contents.RestoreGraphicsState();
            return;
        }
        ////////////////////////////////////////////////////////////////////
        // Draw frame around example area
        ////////////////////////////////////////////////////////////////////

        private void DrawFrameAndBackgroundWaterMark
        (
            PdfContents Contents
        )
        {
            // save graphics state
            Contents.SaveGraphicsState();

            // Draw frame around the page
            // Set line width to 0.02"
            Contents.SetLineWidth(0.02);

            // set frame color dark blue
            Contents.SetColorStroking(Color.DarkBlue);

            // use water mark tiling pattern to fill the frame
            Contents.SetPatternNonStroking(WaterMark);

            // rectangle position: x=1.0", y=1.0", width=6.5", height=9.0"
            Contents.DrawRectangle(1.0, 1.0, 6.5, 9.0, PaintOp.CloseFillStroke);

            // restore graphics sate
            Contents.RestoreGraphicsState();

            // draw article name under the frame
            // Note: the \u00a4 is character 164 that was substituted during Font resource definition
            // this character is a solid circle it is normally unicode 9679 or \u25cf in the Arial family
            Contents.DrawText(ArialNormal, 9.0, 1.1, 0.85, "PdfFileWriter \u00a4 PDF File Writer C# Class Library \u00a4 Author: Uzi Granot");
            return;
        }
        ////////////////////////////////////////////////////////////////////
        // Draw Happy Face
        ////////////////////////////////////////////////////////////////////

        private void DrawHappyFace
        (
            PdfContents Contents
        )
        {
            // save graphics state
            Contents.SaveGraphicsState();

            // translate coordinate origin to the center of the happy face
            Contents.Translate(4.25, 7.5);

            // change nonstroking (fill) color to yellow
            Contents.SetColorNonStroking(Color.Yellow);

            // draw happy face yellow oval
            Contents.DrawOval(-1.5, -1.0, 3.0, 2.0, PaintOp.Fill);

            // set line width to 0.2" this is the black circle around the eye
            Contents.SetLineWidth(0.2);

            // eye color is white with black outline circle
            Contents.SetColorNonStroking(Color.White);
            Contents.SetColorStroking(Color.Black);

            // draw eyes
            Contents.DrawOval(-0.75, 0.0, 0.5, 0.5, PaintOp.CloseFillStroke);
            Contents.DrawOval(0.25, 0.0, 0.5, 0.5, PaintOp.CloseFillStroke);

            // mouth color is black
            Contents.SetColorNonStroking(Color.Black);

            // draw mouth by creating a path made of one line and one Bezier curve
            Contents.MoveTo(-0.6, -0.4);
            Contents.LineTo(0.6, -0.4);
            Contents.DrawBezier(0.0, -0.8, 0, -0.8, -0.6, -0.4);

            // fill the path with black color
            Contents.SetPaintOp(PaintOp.Fill);

            // restore graphics sate
            Contents.RestoreGraphicsState();
            return;
        }
示例#6
0
        ////////////////////////////////////////////////////////////////////
        // Create charting examples PDF document
        ////////////////////////////////////////////////////////////////////

        public void Test
        (
            Boolean Debug,
            String FileName
        )
        {
            // Step 1: Create empty document
            // Arguments: page width: 8.5”, page height: 11”, Unit of measure: inches
            // Return value: PdfDocument main class
            Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);

            // Debug property
            // By default it is set to false. Use it for debugging only.
            // If this flag is set, PDF objects will not be compressed, font and images will be replaced
            // by text place holder. You can view the file with a text editor but you cannot open it with PDF reader.
            Document.Debug = Debug;

            // for encryption test
//		Document.SetEncryption("Password", Permission.All & ~Permission.Print);

            ArialNormal = new PdfFont(Document, "Arial", FontStyle.Regular, true);
            Comic       = new PdfFont(Document, "Comic Sans MS", FontStyle.Bold, true);

            // Step 3: Add new page
            Page = new PdfPage(Document);

            // Step 4:Add contents to page
            PdfContents Contents = new PdfContents(Page);

            // save graphics state
            Contents.SaveGraphicsState();

            // Draw frame around the page
            // Set line width to 0.02"
            Contents.SetLineWidth(0.02);

            // set frame color dark blue
            Contents.SetColorStroking(Color.DarkBlue);
            Contents.SetColorNonStroking(Color.FromArgb(240, 250, 250));

            // rectangle position: x=1.0", y=1.0", width=6.5", height=9.0"
            Contents.DrawRectangle(1.0, 1.0, 6.5, 9.0, PaintOp.CloseFillStroke);
            Contents.DrawLine(1.0, 8.5, 7.5, 8.5);
            Contents.DrawLine(1.0, 6.0, 7.5, 6.0);
            Contents.DrawLine(1.0, 3.5, 7.5, 3.5);

            // page heading
            Contents.DrawText(Comic, 40.0, 4.25, 9.25, TextJustify.Center, 0.02, Color.FromArgb(128, 0, 255), Color.FromArgb(255, 0, 128), "PDF FILE WRITER");

            // change nonstroking (fill) color to purple
            Contents.SetColorNonStroking(Color.Purple);

            // Draw second line of heading text
            // arguments: Handwriting font, Font size 30 point, Position X=4.25", Y=9.0"
            // Text Justify: Center (text center will be at X position)
            Contents.DrawText(Comic, 30.0, 4.25, 8.75, TextJustify.Center, "Media Example");

            // create embedded media file
            Example1();
            Example2();

            // restore graphics sate (non stroking color will be restored to default)
            Contents.RestoreGraphicsState();

            // create the PDF file
            Document.CreateFile();

            // start default PDF reader and display the file
            Process Proc = new Process();

            Proc.StartInfo = new ProcessStartInfo(FileName);
            Proc.Start();

            // exit
            return;
        }
        internal void Draw
        (
            PdfContents Contents,
            double DrawRectX,
            double DrawRectY,
            double DrawRectWidth,
            double DrawRectHeight,
            ContentAlignment Alignment = (ContentAlignment)0
        )
        {
            // save drawing rectangle in user coordinates
            this.DrawRectX      = DrawRectX;
            this.DrawRectY      = DrawRectY;
            this.DrawRectWidth  = DrawRectWidth;
            this.DrawRectHeight = DrawRectHeight;

            // test arguments
            if (DrawRectWidth == 0 && DrawRectHeight == 0 || DrawRectWidth == 0 && PathBBoxWidth != 0 || DrawRectHeight == 0 && PathBBoxHeight != 0)
            {
                throw new ApplicationException("DrawWPFPath: Drawing rectangle is empty");
            }

            // set transformation matrix
            SetTransformation(Alignment);

            // clip
            if (Stroking == null && NonStroking == null)
            {
                // build clipping path
                BuildPath(Contents, FillRule == FillRule.EvenOdd ? PaintOp.ClipPathEor : PaintOp.ClipPathWnr);
                return;
            }

            // paint operator
            PaintOp PaintOperator;

            // brush is defined as shading
            if (NonStroking != null && (NonStroking.GetType() == typeof(SysMedia.LinearGradientBrush) || NonStroking.GetType() == typeof(SysMedia.RadialGradientBrush) ||
                                        NonStroking.GetType() == typeof(PdfAxialShading) || NonStroking.GetType() == typeof(PdfRadialShading)))
            {
                // save graphics state
                Contents.SaveGraphicsState();

                // build clipping path
                BuildPath(Contents, FillRule == FillRule.EvenOdd ? PaintOp.ClipPathEor : PaintOp.ClipPathWnr);

                // set bland mode
                if (BlendMode != BlendMode.Normal)
                {
                    Contents.SetBlendMode(BlendMode);
                }

                // set opacity
                Contents.SetAlphaNonStroking(BrushOpacity);

                // draw linera gradient brush shading bounded by clip path
                if (NonStroking.GetType() == typeof(SysMedia.LinearGradientBrush))
                {
                    PdfAxialShading AxialShading = new PdfAxialShading(Contents.Document, (SysMedia.LinearGradientBrush)NonStroking);
                    AxialShading.SetBoundingBox(DrawRectX, DrawRectY, DrawRectWidth, DrawRectHeight);
                    Contents.DrawShading(AxialShading);
                }

                // draw axial shading bounded by clip path
                else if (NonStroking.GetType() == typeof(PdfAxialShading))
                {
                    ((PdfAxialShading)NonStroking).SetBoundingBox(DrawRectX, DrawRectY, DrawRectWidth, DrawRectHeight);
                    Contents.DrawShading((PdfAxialShading)NonStroking);
                }

                // draw radial gradient brush shading bounded by clip path
                else if (NonStroking.GetType() == typeof(SysMedia.RadialGradientBrush))
                {
                    PdfRadialShading RadialShading = new PdfRadialShading(Contents.Document, (SysMedia.RadialGradientBrush)NonStroking);
                    RadialShading.SetBoundingBox(DrawRectX, DrawRectY, DrawRectWidth, DrawRectHeight);
                    Contents.DrawShading(RadialShading);
                }

                // draw radial shading bounded by clip path
                else
                {
                    ((PdfRadialShading)NonStroking).SetBoundingBox(DrawRectX, DrawRectY, DrawRectWidth, DrawRectHeight);
                    Contents.DrawShading((PdfRadialShading)NonStroking);
                }

                // remove clipping path
                Contents.RestoreGraphicsState();

                // no pen defined
                if (Stroking == null)
                {
                    return;
                }

                // pen is defined
                PaintOperator = PaintOp.Stroke;
            }

            // set paint operator for all other cases (no shading)
            else
            {
                // we have pen and no brush
                if (NonStroking == null)
                {
                    PaintOperator = PaintOp.Stroke;
                }
                // we have brush but no pen
                else if (Stroking == null)
                {
                    PaintOperator = FillRule == FillRule.EvenOdd ? PaintOp.FillEor : PaintOp.Fill;
                }
                // we have brush and pen
                else
                {
                    PaintOperator = FillRule == FillRule.EvenOdd ? PaintOp.CloseFillStrokeEor: PaintOp.CloseFillStroke;
                }
            }

            // save graphics state
            Contents.SaveGraphicsState();

            // set bland mode
            if (BlendMode != BlendMode.Normal)
            {
                Contents.SetBlendMode(BlendMode);
            }

            // stroking (pen) is defined
            if (Stroking != null)
            {
                if (Stroking.GetType() == typeof(Color))
                {
                    // pen color
                    Contents.SetColorStroking((Color)Stroking);

                    // set opacity
                    if (PenOpacity != 1.0)
                    {
                        Contents.SetAlphaStroking(PenOpacity);
                    }

                    // pen width
                    if (PenWidth >= 0)
                    {
                        Contents.SetLineWidth(PenWidth);
                    }

                    // line cap
                    if (LineCap != (PdfLineCap)(-1))
                    {
                        Contents.SetLineCap(LineCap);
                    }

                    // line join
                    if (LineJoin != (PdfLineJoin)(-1))
                    {
                        Contents.SetLineJoin(LineJoin);
                    }

                    // Miter
                    if (MiterLimit != -1)
                    {
                        Contents.SetMiterLimit(MiterLimit);
                    }

                    // line is made of dashes
                    if (DashArray != null)
                    {
                        Contents.SetDashLine(DashArray, DashPhase);
                    }
                }

                else if (Stroking.GetType() == typeof(SysMedia.Pen))
                {
                    // media pen short cut
                    SysMedia.Pen Pen = (SysMedia.Pen)Stroking;

                    // media brush shortcut
                    SysMedia.SolidColorBrush Brush = (SysMedia.SolidColorBrush)Pen.Brush;

                    // media pen color short cut
                    SysMedia.Color PenColor = Brush.Color;

                    // pen color
                    Contents.SetColorStroking(Color.FromArgb(PenColor.R, PenColor.G, PenColor.B));

                    // pen opacity
                    if (PenColor.A != 255 || Brush.Opacity != 1.0)
                    {
                        Contents.SetAlphaStroking((PenColor.A / 255.0) * Brush.Opacity);
                    }

                    // pen thickness converted to user units
                    double Thickness = Pen.Thickness * Math.Max(Math.Abs(ScaleX), Math.Abs(ScaleY));
                    Contents.SetLineWidth(Thickness);

                    // line cap
                    // Note: PDF line cap is the same for start and end. We will ignore EndLineCap
                    // Triangle line cap will be round
                    switch (Pen.StartLineCap)
                    {
                    case SysMedia.PenLineCap.Flat: Contents.SetLineCap(PdfLineCap.Butt); break;

                    case SysMedia.PenLineCap.Square: Contents.SetLineCap(PdfLineCap.Square); break;

                    default: Contents.SetLineCap(PdfLineCap.Round); break;
                    }

                    // line join
                    switch (Pen.LineJoin)
                    {
                    case SysMedia.PenLineJoin.Bevel: Contents.SetLineJoin(PdfLineJoin.Bevel); break;

                    case SysMedia.PenLineJoin.Miter: Contents.SetLineJoin(PdfLineJoin.Miter); break;

                    default: Contents.SetLineJoin(PdfLineJoin.Round); break;
                    }

                    // Miter
                    Contents.SetMiterLimit(Pen.MiterLimit);

                    // dash pattern
                    if (Pen.DashStyle.Dashes.Count > 0)
                    {
                        int      End          = Pen.DashStyle.Dashes.Count;
                        double[] PenDashArray = new double[End];
                        for (int Index = 0; Index < End; Index++)
                        {
                            PenDashArray[Index] = Thickness * Pen.DashStyle.Dashes[Index];
                        }
                        Contents.SetDashLine(PenDashArray, Thickness * Pen.DashStyle.Offset);
                    }
                }
            }

            // non-stroking (brush) is defined
            // note shading brush was handled above
            if (NonStroking != null)
            {
                // set opacity
                if (BrushOpacity != 1.0)
                {
                    Contents.SetAlphaNonStroking(BrushOpacity);
                }

                // brush color
                if (NonStroking.GetType() == typeof(Color))
                {
                    Contents.SetColorNonStroking((Color)NonStroking);
                }

                else if (NonStroking.GetType() == typeof(PdfTilingPattern))
                {
                    Contents.SetPatternNonStroking((PdfTilingPattern)NonStroking);
                }
            }

            // build path
            BuildPath(Contents, PaintOperator);

            // restore graphics state
            Contents.RestoreGraphicsState();
            return;
        }
        ////////////////////////////////////////////////////////////////////
        // Draw example of order form
        ////////////////////////////////////////////////////////////////////

        private void DrawBookOrderForm
        (
            PdfContents Contents
        )
        {
            // Order form simulation
            // Define constants to make the code readable
            // Define constants
            const Double Width        = 3.05;
            const Double Height       = 3.65;
            const Double Margin       = 0.04;
            const Double FontSize     = 9.0;
            Double       LineSpacing  = ArialNormal.LineSpacing(FontSize);
            Double       Descent      = ArialNormal.Descent(FontSize);
            Double       ColWidth1    = ArialNormal.TextWidth(FontSize, "9999.99") + 2 * Margin;
            Double       ColWidth2    = ArialNormal.TextWidth(FontSize, "Qty") + 2 * Margin;
            Double       Col4LinePosX = Width - ColWidth1;
            Double       Col3LinePosX = Col4LinePosX - ColWidth2;
            Double       Col2LinePosX = Col3LinePosX - ColWidth1;
            Double       Col1TextPosX = Margin;
            Double       Col2TextPosX = Col3LinePosX - Margin;
            Double       Col3TextPosX = Col4LinePosX - Margin;
            Double       Col4TextPosX = Width - Margin;

            // save graphics state
            Contents.SaveGraphicsState();

            // form line width 0.01"
            Contents.SetLineWidth(0.01);

            // Initial vertical position for contents
            Double PosY1 = Height - LineSpacing - 2 * Margin;

            // bottom of the contents area of the form
            Double PosY2 = 2 * Margin + 3 * LineSpacing;

            // shift origin, bottom left of the form to X=4.35" and Y=1.1"
            Contents.Translate(4.35, 1.1);

            // draw outline rectangle
            Contents.DrawRectangle(0.0, 0.0, Width, Height, PaintOp.CloseStroke);

            // draw two horizontal lines. under table heading and above total
            Contents.DrawLine(0, PosY1, Width, PosY1);
            Contents.DrawLine(0, PosY2, Width, PosY2);

            // draw three vertical lines separating the columns
            Contents.DrawLine(Col2LinePosX, Height, Col2LinePosX, PosY2);
            Contents.DrawLine(Col3LinePosX, Height, Col3LinePosX, PosY2);
            Contents.DrawLine(Col4LinePosX, Height, Col4LinePosX, 0);

            // draw table heading
            Double PosY = PosY1 + Margin + Descent;

            Contents.DrawText(ArialNormal, FontSize, Col1TextPosX, PosY, "Description");
            Contents.DrawText(ArialNormal, FontSize, Col2TextPosX, PosY, TextJustify.Right, "Price");
            Contents.DrawText(ArialNormal, FontSize, Col3TextPosX, PosY, TextJustify.Right, "Qty");
            Contents.DrawText(ArialNormal, FontSize, Col4TextPosX, PosY, TextJustify.Right, "Total");

            // reset order total
            Double Total = 0;

            // define text box for book title and author
            TextBox Box = new TextBox(Col2LinePosX - 2 * Margin);

            // initial vertical position
            PosY = PosY1 - Margin;

            // loop for all items in the order
            // Order class is a atabase simulation for this example
            foreach (Order Book in Order.OrderList)
            {
                // clear the text box
                Box.Clear();

                // add book title and authors to the box
                Box.AddText(ArialNormal, FontSize, Book.Title);
                Box.AddText(ArialNormal, FontSize, ". By: ");
                Box.AddText(ArialNormal, FontSize, Book.Authors);

                // draw the title and authors.
                // on exit, PosY will be for next line
                Contents.DrawText(Col1TextPosX, ref PosY, PosY2, 0, Box);

                // move PosY up to allow drawing cost on the same line as the last text line of the box
                PosY += Descent;

                // draw price quantity and item's total
                Contents.DrawText(ArialNormal, FontSize, Col2TextPosX, PosY, TextJustify.Right, Book.Price.ToString("#.00"));
                Contents.DrawText(ArialNormal, FontSize, Col3TextPosX, PosY, TextJustify.Right, Book.Qty.ToString());
                Contents.DrawText(ArialNormal, FontSize, Col4TextPosX, PosY, TextJustify.Right, Book.Total.ToString("#.00"));

                // update PosY for next item
                PosY -= Descent + 0.5 * LineSpacing;

                // accumulate total
                Total += Book.Total;
            }

            // draw total before tax
            PosY = PosY2 - Margin - ArialNormal.Ascent(FontSize);
            Contents.DrawText(ArialNormal, FontSize, Col3TextPosX, PosY, TextJustify.Right, "Total before tax");
            Contents.DrawText(ArialNormal, FontSize, Col4TextPosX, PosY, TextJustify.Right, Total.ToString("#.00"));

            // draw tax (Ontario Canada HST)
            PosY -= LineSpacing;
            Contents.DrawText(ArialNormal, FontSize, Col3TextPosX, PosY, TextJustify.Right, "Tax (13%)");
            Double Tax = Math.Round(0.13 * Total, 2, MidpointRounding.AwayFromZero);

            Contents.DrawText(ArialNormal, FontSize, Col4TextPosX, PosY, TextJustify.Right, Tax.ToString("#.00"));

            // draw final total
            PosY -= LineSpacing;
            Contents.DrawText(ArialNormal, FontSize, Col3TextPosX, PosY, TextJustify.Right, "Total payable");
            Total += Tax;
            Contents.DrawText(ArialNormal, FontSize, Col4TextPosX, PosY, TextJustify.Right, Total.ToString("#.00"));

            // restore graphics state
            Contents.RestoreGraphicsState();
            return;
        }
示例#9
0
        public void Test
        (
            bool Debug,
            string InputFileName
        )
        {
            // create document
            using (Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, InputFileName))
            {
                // set document page mode to open the layers panel
                Document.InitialDocDisplay = InitialDocDisplay.UseLayers;

                // define font
                ArialFont = PdfFont.CreatePdfFont(Document, "Arial", FontStyle.Bold);

                // open layer control object (in PDF terms optional content object)
                PdfLayers Layers = new PdfLayers(Document, "PDF layers group");

                // set layer panel to incluse all layers including ones that are not visible
                Layers.ListMode = ListMode.AllPages;

                // Add new page
                PdfPage Page = new PdfPage(Document);

                // Add contents to page
                PdfContents Contents = new PdfContents(Page);

                // heading
                Contents.DrawText(ArialFont, 24, 4.25, 10, TextJustify.Center, "PDF File Writer Layer Test/Demo");

                // define layers
                PdfLayer DrawingTest    = new PdfLayer(Layers, "Drawing Test");
                PdfLayer Rectangle      = new PdfLayer(Layers, "Rectangle");
                PdfLayer HorLines       = new PdfLayer(Layers, "Horizontal Lines");
                PdfLayer VertLines      = new PdfLayer(Layers, "Vertical Lines");
                PdfLayer QRCodeLayer    = new PdfLayer(Layers, "QRCode barcode");
                PdfLayer Pdf417Layer    = new PdfLayer(Layers, "PDF417 barcode");
                PdfLayer NoBarcodeLayer = new PdfLayer(Layers, "No barcode");

                // combine three layers into one group of radio buttons
                QRCodeLayer.RadioButton    = "Barcode";
                Pdf417Layer.RadioButton    = "Barcode";
                NoBarcodeLayer.RadioButton = "Barcode";

                // set the order of layers in the layer pane
                Layers.DisplayOrder(DrawingTest);
                Layers.DisplayOrder(Rectangle);
                Layers.DisplayOrder(HorLines);
                Layers.DisplayOrder(VertLines);
                Layers.DisplayOrderStartGroup("Barcode group");
                Layers.DisplayOrder(QRCodeLayer);
                Layers.DisplayOrder(Pdf417Layer);
                Layers.DisplayOrder(NoBarcodeLayer);
                Layers.DisplayOrderEndGroup();

                // start a group layer
                Contents.LayerStart(DrawingTest);

                // sticky note annotation
                PdfAnnotation StickyNote = Page.AddStickyNote(2.0, 9.0, "My sticky note", StickyNoteIcon.Note);
                StickyNote.LayerControl = DrawingTest;

                // draw a single layer
                Contents.LayerStart(Rectangle);
                Contents.DrawText(ArialFont, 14, 1.0, 8.0, TextJustify.Left, "Draw rectangle");
                Contents.LayerEnd();

                // draw a single layer
                Contents.LayerStart(HorLines);
                Contents.DrawText(ArialFont, 14, 1.0, 7.5, TextJustify.Left, "Draw horizontal lines");
                Contents.LayerEnd();

                // draw a single layer
                Contents.LayerStart(VertLines);
                Contents.DrawText(ArialFont, 14, 1.0, 7.0, TextJustify.Left, "Draw vertical lines");
                Contents.LayerEnd();

                double Left   = 4.0;
                double Right  = 7.0;
                double Top    = 9.0;
                double Bottom = 6.0;

                // draw a single layer
                Contents.LayerStart(Rectangle);
                Contents.SaveGraphicsState();
                Contents.SetLineWidth(0.1);
                Contents.SetColorStroking(Color.Black);
                Contents.SetColorNonStroking(Color.LightBlue);
                Contents.DrawRectangle(Left, Bottom, 3.0, 3.0, PaintOp.CloseFillStroke);
                Contents.RestoreGraphicsState();
                Contents.LayerEnd();

                // save graphics state
                Contents.SaveGraphicsState();

                // draw a single layer
                Contents.SetLineWidth(0.02);
                Contents.LayerStart(HorLines);
                for (int Row = 1; Row < 6; Row++)
                {
                    Contents.DrawLine(Left, Bottom + 0.5 * Row, Right, Bottom + 0.5 * Row);
                }
                Contents.LayerEnd();

                // draw a single layer
                Contents.LayerStart(VertLines);
                for (int Col = 1; Col < 6; Col++)
                {
                    Contents.DrawLine(Left + 0.5 * Col, Bottom, Left + 0.5 * Col, Top);
                }
                Contents.LayerEnd();

                // restore graphics state
                Contents.RestoreGraphicsState();

                // terminate a group of layers
                Contents.LayerEnd();

                // define QRCode barcode
                QREncoder QREncoder = new QREncoder();
                QREncoder.ErrorCorrection = ErrorCorrection.M;
                QREncoder.Encode(QRCodeArticle);
                PdfImage QRImage = new PdfImage(Document);
                QRImage.LoadImage(QREncoder);

                // define PDF417 barcode
                Pdf417Encoder Pdf417Encoder = new Pdf417Encoder();
                Pdf417Encoder.ErrorCorrection = ErrorCorrectionLevel.AutoMedium;
                Pdf417Encoder.Encode(Pdf417Article);
                PdfImage Pdf417Image = new PdfImage(Document);
                Pdf417Image.LoadImage(Pdf417Encoder);

                // draw a single layer
                Contents.LayerStart(QRCodeLayer);
                Contents.DrawText(ArialFont, 14, 1.0, 2.5, TextJustify.Left, "QRCode Barcode");
                Contents.DrawImage(QRImage, 3.7, 2.5 - 1.75, 3.5);
                Contents.LayerEnd();

                // draw a single layer
                Contents.LayerStart(Pdf417Layer);
                Contents.DrawText(ArialFont, 14, 1.0, 2.5, TextJustify.Left, "PDF417 Barcode");
                Contents.DrawImage(Pdf417Image, 3.7, 2.5 - 1.75 * Pdf417Encoder.ImageHeight / Pdf417Encoder.ImageWidth, 3.5);
                Contents.LayerEnd();

                // draw a single layer
                Contents.LayerStart(NoBarcodeLayer);
                Contents.DrawText(ArialFont, 14, 1.0, 3.0, TextJustify.Left, "Display no barcode");
                Contents.LayerEnd();

                // create pdf file
                Document.CreateFile();

                // start default PDF reader and display the file
                Process Proc = new Process();
                Proc.StartInfo = new ProcessStartInfo(InputFileName);
                Proc.Start();
            }
            return;
        }
示例#10
0
        public FileInfo CreateOfferDocument(Offer offer, bool asOrder = false, bool withPreview = true)
        {
            ResetVars();
            myOffer = offer;
            PdfDocument  doc;
            PdfPage      page;
            PdfContents  content;
            PdfImage     img;
            double       lineSpacing;
            double       descent;
            const double fontSize = 10.0;
            bool         isOffer  = (this.myOffer.Bestellkennzeichen | asOrder);

            string fullName = Path.Combine(CatalistRegistry.Application.OfferFilePath, offer.OfferId + ".pdf");

            doc       = new PdfDocument(PaperType.A4, false, UnitOfMeasure.mm, fullName);
            doc.Debug = false;
            page      = new PdfPage(doc);
            content   = new PdfContents(page);
            content.SetLineWidth(0.03);

            fontDefault    = new PdfFont(doc, "Calibri", System.Drawing.FontStyle.Regular, true);
            myFontBold     = new PdfFont(doc, "Calibri", System.Drawing.FontStyle.Bold, true);
            fontFooter     = new PdfFont(doc, "Calibri Light", System.Drawing.FontStyle.Regular, true);
            fontFooterBold = new PdfFont(doc, "Calibri Light", System.Drawing.FontStyle.Bold, true);
            fontPriceTotal = new PdfFont(doc, "Calibri Light", System.Drawing.FontStyle.Bold, true);

            lineSpacing = fontDefault.LineSpacing(fontSize);
            descent     = fontDefault.Descent(fontSize);

            // Header
            string imagePath = Path.Combine(CatalistRegistry.Application.PicturePath, "briefkopf.png");

            img = new PdfImage(doc, imagePath);
            content.DrawImage(img, 5, pageHeight - 27.9 - 5, 199.6, 27.4);
            content.DrawLine(xLeftMargin - 5, pageHeight - 27.9 - 5 - 2, xRightMargin + 5, pageHeight - 27.9 - 5 - 2);

            string absender = @"Cut & Print Media GmbH & Co. KG · Osterheide 9 · 49124 Georgsmarienhütte";

            content.DrawText(fontDefault, fontSize - 4, 18, pageHeight - 49.5, absender);
            content.DrawLine(18, pageHeight - 50.5, 84.5, pageHeight - 50.5, 0.1);
            content.DrawText(fontDefault, fontSize + 2, 18, pageHeight - 55, offer.Customer.CompanyName1);
            content.DrawText(fontDefault, fontSize + 2, 18, pageHeight - 65, offer.Customer.Street);
            string zipCity = string.Format("{0} {1}", offer.Customer.ZipCode, offer.Customer.City);

            content.DrawText(fontDefault, fontSize + 2, 18, pageHeight - 71, zipCity);

            string vorgang = isOffer ? "Bestellung" : "Angebot";

            content.DrawText(fontDefault, fontSize + 2, xVLine3 + 5, pageHeight - 55, "Kunden-Nr.:");
            content.DrawText(fontDefault, fontSize + 2, xVLine5 - 13, pageHeight - 55, offer.CustomerId.Substring(0, 5));
            content.DrawText(fontDefault, fontSize + 2, xVLine3 + 5, pageHeight - 60, vorgang + " Nr.:");
            content.DrawText(fontDefault, fontSize + 2, xVLine5 - 13, pageHeight - 60, offer.OfferId);
            content.DrawText(fontDefault, fontSize + 2, xVLine3 + 5, pageHeight - 65, "Datum:");
            content.DrawText(fontDefault, fontSize + 2, xVLine5 - 13, pageHeight - 65, offer.ChangeDate.ToShortDateString());
            content.DrawText(fontDefault, fontSize + 2, xVLine3 + 5, pageHeight - 70, "Bearbeitet von:");
            content.DrawText(fontDefault, fontSize + 2, xVLine5 - 13, pageHeight - 70, offer.ChangeUser);

            content.DrawText(myFontBold, fontSize + 2, 10, pageHeight - 96.5, vorgang + " " + offer.OfferId);

            var table = new PdfTable(page, content, fontDefault, 9);

            table.TableStartEvent += tab_TableStartEvent;
            table.TableEndEvent   += tab_TableEndEvent;
            table.TableArea        = new PdfRectangle(10D, 35D, 200D, pageHeight - 40);
            table.RowTopPosition   = pageHeight - 100D;           // 10cm vom oberen Rand
            table.SetColumnWidth(9D, 34D, 86D, 13D, 19D, 19D);
            table.HeaderOnEachPage = true;

            table.Header[colPos].Style           = table.HeaderStyle;
            table.Header[colPos].Style.Alignment = System.Drawing.ContentAlignment.MiddleRight;
            table.Header[colPos].Value           = "Pos.";

            table.Header[colArtNr].Value  = "Artikel-Nr.";
            table.Header[colArtBez].Value = "Artikelbezeichnung";

            table.Header[colMenge].Style           = table.HeaderStyle;
            table.Header[colMenge].Style.Alignment = System.Drawing.ContentAlignment.MiddleRight;
            table.Header[colMenge].Value           = "Menge";

            table.Header[colPreis].Style           = table.HeaderStyle;
            table.Header[colPreis].Style.Alignment = System.Drawing.ContentAlignment.MiddleRight;
            table.Header[colPreis].Value           = "Einzelpreis";

            table.Header[colGesamt].Style           = table.HeaderStyle;
            table.Header[colGesamt].Style.Alignment = System.Drawing.ContentAlignment.MiddleRight;
            table.Header[colGesamt].Value           = "Gesamtpreis";

            table.DefaultHeaderStyle.Font          = myFontBold;
            table.DefaultHeaderStyle.Alignment     = System.Drawing.ContentAlignment.TopLeft;
            table.DefaultHeaderStyle.MultiLineText = false;

            table.DefaultCellStyle.Font      = fontDefault;
            table.DefaultCellStyle.FontSize  = 9;
            table.DefaultCellStyle.Alignment = System.Drawing.ContentAlignment.TopLeft;

            table.Cell[colPos].Style           = table.CellStyle;
            table.Cell[colPos].Style.Alignment = System.Drawing.ContentAlignment.TopRight;

            table.Cell[colArtNr].Style = table.CellStyle;
            table.Cell[colArtNr].Style.TextBoxTextJustify = TextBoxJustify.Left;

            table.Cell[colArtBez].Style = table.CellStyle;
            table.Cell[colArtBez].Style.TextBoxTextJustify = TextBoxJustify.Left;

            table.Cell[colMenge].Style           = table.CellStyle;
            table.Cell[colMenge].Style.Format    = "#,##0";
            table.Cell[colMenge].Style.Alignment = System.Drawing.ContentAlignment.TopRight;

            table.Cell[colPreis].Style           = table.CellStyle;
            table.Cell[colPreis].Style.Format    = "#,##0.00";
            table.Cell[colPreis].Style.Alignment = System.Drawing.ContentAlignment.TopRight;

            table.Cell[colGesamt].Style = table.CellStyle;
            table.Cell[colGesamt].Style.ForegroundColor = System.Drawing.Color.DarkRed;
            table.Cell[colGesamt].Style.Format          = "#,##0.00";
            table.Cell[colGesamt].Style.Alignment       = System.Drawing.ContentAlignment.TopRight;

            int dCount = offer.OfferDetails.Count;

            for (int i = 0; i < dCount; i++)
            {
                lastRow |= i == dCount - 1;

                table.Cell[colPos].Value   = offer.OfferDetails[i].Position;
                table.Cell[colArtNr].Value = offer.OfferDetails[i].Artikelnummer;
                TextBox txtBezeichnung = table.Cell[colArtBez].CreateTextBox();
                txtBezeichnung.AddText(myFontBold, 9, offer.OfferDetails[i].Artikelname);
                if (!isOffer)
                {
                    txtBezeichnung.AddText(fontDefault, 9, string.Format("\n\n{0}", offer.OfferDetails[i].Artikeltext.Replace("\t", " ")));
                }
                table.Cell[colMenge].Value = string.Format("{0:#,##0} {1}", offer.OfferDetails[i].Menge, offer.OfferDetails[i].Einheit);

                if (!isOffer)
                {
                    table.Cell[colPreis].Value  = offer.OfferDetails[i].Kundenpreis;
                    table.Cell[colGesamt].Value = offer.OfferDetails[i].Zeilensumme;
                    zwischenSumme += offer.OfferDetails[i].Zeilensumme;
                }
                else
                {
                    table.Cell[colPreis].Value  = "-";
                    table.Cell[colGesamt].Value = "-";
                }
                table.DrawRow(offer.OfferDetails[i].NeueSeite);
            }
            table.Close();

            try
            {
                doc.CreateFile();
                if (File.Exists(fullName) && withPreview)
                {
                    // Datei in das lokale TEMP Verzeichnis kopieren
                    var    temp            = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string prefix          = asOrder ? "B" : "A";
                    var    tempFilename    = string.Format("{0}{1}.pdf", prefix, DateTime.Now.ToString("yyyy-MM-dd_hh.mm.ss"));
                    var    tempFileAndPath = Path.Combine(temp, tempFilename);
                    File.Copy(fullName, tempFileAndPath);
                    var proc = new Process();
                    proc.StartInfo = new ProcessStartInfo(tempFileAndPath);
                    proc.Start();
                }

                return(new FileInfo(fullName));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }