Example #1
0
            internal void Initialize(
                )
            {
                // State parameters initialization.
                blendMode        = ExtGState.DefaultBlendMode;
                charSpace        = 0;
                ctm              = GetInitialCtm();
                fillColor        = colors::DeviceGrayColor.Default;
                fillColorSpace   = colors::DeviceGrayColorSpace.Default;
                font             = null;
                fontSize         = 0;
                lead             = 0;
                lineCap          = LineCapEnum.Butt;
                lineDash         = new LineDash();
                lineJoin         = LineJoinEnum.Miter;
                lineWidth        = 1;
                miterLimit       = 10;
                renderMode       = TextRenderModeEnum.Fill;
                rise             = 0;
                scale            = 100;
                strokeColor      = colors::DeviceGrayColor.Default;
                strokeColorSpace = colors::DeviceGrayColorSpace.Default;
                tlm              = new Matrix();
                tm        = new Matrix();
                wordSpace = 0;

                // Rendering context initialization.
                Graphics renderContext = Scanner.RenderContext;

                if (renderContext != null)
                {
                    renderContext.Transform = ctm;
                }
            }
 public StampAppearanceBuilder(Document document, TypeEnum type, string text, float width, fonts::Font font)
 {
     this.document = document;
     this.type     = type;
     this.width    = width;
     Text          = text;
     Font          = font;
 }
Example #3
0
        public override ContentObject ToInlineObject(PrimitiveComposer composer)
        {
            ContentObject barcodeObject = composer.BeginLocalState();

            {
                fonts::Font font     = fonts::PdfType1Font.Load(composer.Scanner.Contents.Document, fonts::PdfType1Font.FamilyEnum.Helvetica, false, false);
                double      fontSize = (DigitGlyphWidth / font.GetWidth(code.Substring(0, 1), 1));

                // 1. Bars.
                {
                    double elementX      = DigitWidth;
                    int[]  elementWidths = GetElementWidths();

                    double guardBarIndentY = DigitHeight / 2;
                    bool   isBar           = true;
                    for (int elementIndex = 0; elementIndex < elementWidths.Length; elementIndex++)
                    {
                        double elementWidth = elementWidths[elementIndex];
                        // Dark element?

                        /*
                         * NOTE: EAN symbol elements alternate bars to spaces.
                         */
                        if (isBar)
                        {
                            composer.DrawRectangle(
                                SKRect.Create(
                                    (float)elementX,
                                    0,
                                    (float)elementWidth,
                                    (float)(BarHeight + (
                                                // Guard bar?
                                                Array.BinarySearch <int>(GuardBarIndexes, elementIndex) >= 0
                                    ? guardBarIndentY // Guard bar.
                                    : 0               // Symbol character.
                                                ))
                                    )
                                );
                        }

                        elementX += elementWidth;
                        isBar     = !isBar;
                    }
                    composer.Fill();
                }

                // 2. Digits.
                {
                    composer.SetFont(font, fontSize);
                    double digitY = BarHeight + (DigitHeight - (font.GetAscent(fontSize))) / 2;
                    // Showing the digits...
                    for (int digitIndex = 0; digitIndex < 13; digitIndex++)
                    {
                        string digit = code.Substring(digitIndex, 1);
                        double pX    = DigitGlyphXs[digitIndex]              // Digit position.
                                       - font.GetWidth(digit, fontSize) / 2; // Centering.
                                                                             // Show the current digit!
                        composer.ShowText(
                            digit,
                            new SKPoint((float)pX, (float)digitY)
                            );
                    }
                }
                composer.End();
            }
            return(barcodeObject);
        }
Example #4
0
        private void Populate(Document document)
        {
            Page page = new Page(document);

            document.Pages.Add(page);

            PrimitiveComposer        composer = new PrimitiveComposer(page);
            fonts::StandardType1Font font     = new fonts::StandardType1Font(document, fonts::StandardType1Font.FamilyEnum.Courier, true, false);

            composer.SetFont(font, 12);

            // Sticky note.
            composer.ShowText("Sticky note annotation:", new SKPoint(35, 35));
            new StickyNote(page, new SKPoint(50, 50), "Text of the Sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Note,
                Color    = DeviceRGBColor.Get(SKColors.Yellow),
                Popup    = new Popup(
                    page,
                    SKRect.Create(200, 25, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    ),
                Author  = "Stefano",
                Subject = "Sticky note",
                IsOpen  = true
            };
            new StickyNote(page, new SKPoint(80, 50), "Text of the Help sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Help,
                Color    = DeviceRGBColor.Get(SKColors.Pink),
                Author   = "Stefano",
                Subject  = "Sticky note",
                Popup    = new Popup(
                    page,
                    SKRect.Create(400, 25, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    )
            };
            new StickyNote(page, new SKPoint(110, 50), "Text of the Comment sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Comment,
                Color    = DeviceRGBColor.Get(SKColors.Green),
                Author   = "Stefano",
                Subject  = "Sticky note"
            };
            new StickyNote(page, new SKPoint(140, 50), "Text of the Key sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Key,
                Color    = DeviceRGBColor.Get(SKColors.Blue),
                Author   = "Stefano",
                Subject  = "Sticky note"
            };

            // Callout.
            composer.ShowText("Callout note annotation:", new SKPoint(35, 85));
            new FreeText(page, SKRect.Create(250, 90, 150, 70), "Text of the Callout note annotation")
            {
                Line = new FreeText.CalloutLine(
                    page,
                    new SKPoint(100, 100),
                    new SKPoint(150, 125),
                    new SKPoint(250, 125)
                    ),
                Type         = FreeText.TypeEnum.Callout,
                LineEndStyle = LineEndStyleEnum.OpenArrow,
                Border       = new Border(1),
                Color        = DeviceRGBColor.Get(SKColors.Yellow)
            };

            // File attachment.
            composer.ShowText("File attachment annotation:", new SKPoint(35, 135));
            new FileAttachment(
                page,
                SKRect.Create(50, 150, 15, 20),
                "Text of the File attachment annotation",
                FileSpecification.Get(
                    EmbeddedFile.Get(document, GetResourcePath("images" + Path.DirectorySeparatorChar + "gnu.jpg")),
                    "happyGNU.jpg")
                )
            {
                IconType = FileAttachment.IconTypeEnum.PaperClip,
                Author   = "Stefano",
                Subject  = "File attachment"
            };

            composer.ShowText("Line annotation:", new SKPoint(35, 185));
            {
                composer.BeginLocalState();
                composer.SetFont(font, 10);

                // Arrow line.
                composer.ShowText("Arrow:", new SKPoint(50, 200));
                new Line(
                    page,
                    new SKPoint(50, 260),
                    new SKPoint(200, 210),
                    "Text of the Arrow line annotation",
                    DeviceRGBColor.Get(SKColors.Black))
                {
                    StartStyle     = LineEndStyleEnum.Circle,
                    EndStyle       = LineEndStyleEnum.ClosedArrow,
                    CaptionVisible = true,
                    FillColor      = DeviceRGBColor.Get(SKColors.Green),
                    Author         = "Stefano",
                    Subject        = "Arrow line"
                };

                // Dimension line.
                composer.ShowText("Dimension:", new SKPoint(300, 200));
                new Line(
                    page,
                    new SKPoint(300, 220),
                    new SKPoint(500, 220),
                    "Text of the Dimension line annotation",
                    DeviceRGBColor.Get(SKColors.Blue)
                    )
                {
                    LeaderLineLength          = 20,
                    LeaderLineExtensionLength = 10,
                    StartStyle     = LineEndStyleEnum.OpenArrow,
                    EndStyle       = LineEndStyleEnum.OpenArrow,
                    Border         = new Border(1),
                    CaptionVisible = true,
                    Author         = "Stefano",
                    Subject        = "Dimension line"
                };

                composer.End();
            }

            var path = new SKPath();

            path.MoveTo(new SKPoint(50, 320));
            path.LineTo(new SKPoint(70, 305));
            path.LineTo(new SKPoint(110, 335));
            path.LineTo(new SKPoint(130, 320));
            path.LineTo(new SKPoint(110, 305));
            path.LineTo(new SKPoint(70, 335));
            path.LineTo(new SKPoint(50, 320));
            // Scribble.
            composer.ShowText("Scribble annotation:", new SKPoint(35, 285));
            new Scribble(
                page,
                new List <SKPath> {
                path
            },
                "Text of the Scribble annotation",
                DeviceRGBColor.Get(SKColors.Orange))
            {
                Border  = new Border(1, new LineDash(new double[] { 5, 2, 2, 2 })),
                Author  = "Stefano",
                Subject = "Scribble"
            };

            // Rectangle.
            composer.ShowText("Rectangle annotation:", new SKPoint(35, 350));
            new PdfClown.Documents.Interaction.Annotations.Rectangle(
                page,
                SKRect.Create(50, 370, 100, 30),
                "Text of the Rectangle annotation")
            {
                Color   = DeviceRGBColor.Get(SKColors.Red),
                Border  = new Border(1, new LineDash(new double[] { 5 })),
                Author  = "Stefano",
                Subject = "Rectangle",
                Popup   = new Popup(
                    page,
                    SKRect.Create(200, 325, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    )
            };

            // Ellipse.
            composer.ShowText("Ellipse annotation:", new SKPoint(35, 415));
            new Ellipse(
                page,
                SKRect.Create(50, 440, 100, 30),
                "Text of the Ellipse annotation")
            {
                BorderEffect = new BorderEffect(BorderEffect.TypeEnum.Cloudy, 1),
                FillColor    = DeviceRGBColor.Get(SKColors.Cyan),
                Color        = DeviceRGBColor.Get(SKColors.Black),
                Author       = "Stefano",
                Subject      = "Ellipse"
            };

            // Rubber stamp.
            composer.ShowText("Rubber stamp annotations:", new SKPoint(35, 505));
            {
                fonts::Font stampFont = fonts::Font.Get(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "TravelingTypewriter.otf"));
                new Stamp(
                    page,
                    new SKPoint(75, 570),
                    "This is a round custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Round, "Done", 50, stampFont)
                    .Build()
                    )
                {
                    Rotation = -10,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                new Stamp(
                    page,
                    new SKPoint(210, 570),
                    "This is a squared (and round-cornered) custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Squared, "Classified", 150, stampFont)
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                }.Build()
                    )
                {
                    Rotation = 15,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                fonts::Font stampFont2 = fonts::Font.Get(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "MgOpenCanonicaRegular.ttf"));
                new Stamp(
                    page,
                    new SKPoint(350, 570),
                    "This is a striped custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Striped, "Out of stock", 100, stampFont2)
                {
                    Color = DeviceRGBColor.Get(SKColors.Gray)
                }.Build()
                    )
                {
                    Rotation = 90,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                // Define the standard stamps template path!

                /*
                 * NOTE: The PDF specification defines several stamps (aka "standard stamps") whose rendering
                 * depends on the support of viewer applications. As such support isn't guaranteed, PDF Clown
                 * offers smooth, ready-to-use embedding of these stamps through the StampPath property of the
                 * document configuration: you can decide to point to the stamps directory of your Acrobat
                 * installation (e.g., in my GNU/Linux system it's located in
                 * "/opt/Adobe/Reader9/Reader/intellinux/plug_ins/Annotations/Stamps/ENU") or to the
                 * collection included in this distribution (std-stamps.pdf).
                 */
                document.Configuration.StampPath = GetResourcePath("../../pkg/templates/std-stamps.pdf");

                // Add a standard stamp, rotating it 15 degrees counterclockwise!
                new Stamp(
                    page,
                    new SKPoint(485, 515),
                    null, // Default size is natural size.
                    "This is 'Confidential', a standard stamp",
                    StandardStampEnum.Confidential)
                {
                    Rotation = 15,
                    Author   = "Stefano",
                    Subject  = "Standard stamp"
                };

                // Add a standard stamp, without rotation!
                new Stamp(
                    page,
                    new SKPoint(485, 580),
                    null, // Default size is natural size.
                    "This is 'SBApproved', a standard stamp",
                    StandardStampEnum.BusinessApproved)
                {
                    Author  = "Stefano",
                    Subject = "Standard stamp"
                };

                // Add a standard stamp, rotating it 10 degrees clockwise!
                new Stamp(
                    page,
                    new SKPoint(485, 635),
                    new SKSize(0, 40), // This scales the width proportionally to the 40-unit height (you can obviously do also the opposite, defining only the width).
                    "This is 'SHSignHere', a standard stamp",
                    StandardStampEnum.SignHere)
                {
                    Rotation = -10,
                    Author   = "Stefano",
                    Subject  = "Standard stamp"
                };
            }

            composer.ShowText("Text markup annotations:", new SKPoint(35, 650));
            {
                composer.BeginLocalState();
                composer.SetFont(font, 8);

                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation", new SKPoint(35, 680)),
                    "Text of the Highlight annotation",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Author  = "Stefano",
                    Subject = "An highlight text markup!"
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation 2", new SKPoint(35, 695)).Inflate(0, 1),
                    "Text of the Highlight annotation 2",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Color = DeviceRGBColor.Get(SKColors.Magenta)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation 3", new SKPoint(35, 710)).Inflate(0, 2),
                    "Text of the Highlight annotation 3",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Color = DeviceRGBColor.Get(SKColors.Red)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation", new SKPoint(180, 680)),
                    "Text of the Squiggly annotation",
                    TextMarkup.MarkupTypeEnum.Squiggly);
                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation 2", new SKPoint(180, 695)).Inflate(0, 2.5f),
                    "Text of the Squiggly annotation 2",
                    TextMarkup.MarkupTypeEnum.Squiggly)
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation 3", new SKPoint(180, 710)).Inflate(0, 3),
                    "Text of the Squiggly annotation 3",
                    TextMarkup.MarkupTypeEnum.Squiggly)
                {
                    Color = DeviceRGBColor.Get(SKColors.Pink)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation", new SKPoint(320, 680)),
                    "Text of the Underline annotation",
                    TextMarkup.MarkupTypeEnum.Underline
                    );
                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation 2", new SKPoint(320, 695)).Inflate(0, 2.5f),
                    "Text of the Underline annotation 2",
                    TextMarkup.MarkupTypeEnum.Underline
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation 3", new SKPoint(320, 710)).Inflate(0, 3),
                    "Text of the Underline annotation 3",
                    TextMarkup.MarkupTypeEnum.Underline
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Green)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation", new SKPoint(455, 680)),
                    "Text of the StrikeOut annotation",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    );
                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation 2", new SKPoint(455, 695)).Inflate(0, 2.5f),
                    "Text of the StrikeOut annotation 2",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation 3", new SKPoint(455, 710)).Inflate(0, 3),
                    "Text of the StrikeOut annotation 3",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Green)
                };

                composer.End();
            }
            composer.Flush();
        }
Example #5
0
        /**
         * <summary>Shows text.</summary>
         * <returns>Last shown character index.</returns>
         */
        public int ShowText(
            string text
            )
        {
            if (currentRow == null ||
                text == null)
            {
                return(0);
            }

            ContentScanner.GraphicsState state = baseComposer.State;
            fonts::Font font       = state.Font;
            float       fontSize   = state.FontSize;
            float       lineHeight = font.GetLineHeight(fontSize);

            TextFitter textFitter = new TextFitter(
                text,
                0,
                font,
                fontSize,
                hyphenation
                );
            int textLength = text.Length;
            int index      = 0;

            while (true)
            {
                // Beginning of current row?
                if (currentRow.Width == 0)
                {
                    // Removing leading space...
                    while (true)
                    {
                        // Did we reach the text end?
                        if (index == textLength)
                        {
                            goto endTextShowing; // NOTE: I know GOTO is evil, yet in this case it's a much cleaner solution.
                        }
                        if (text[index] != ' ')
                        {
                            break;
                        }

                        index++;
                    }
                }

                // Text height: exceeds current row's height?
                if (lineHeight > currentRow.Height)
                {
                    // Text height: exceeds block's remaining vertical space?
                    if (lineHeight > frame.Height - currentRow.Y) // Text exceeds.
                    {
                        // Terminate the current row!
                        EndRow(false);
                        goto endTextShowing; // NOTE: I know GOTO is evil, yet in this case it's a much cleaner solution.
                    }
                    else // Text doesn't exceed.
                    {
                        // Adapt current row's height!
                        currentRow.Height = lineHeight;
                    }
                }

                // Does the text fit?
                if (textFitter.Fit(
                        index,
                        frame.Width - currentRow.Width // Residual row width.
                        ))
                {
                    // Get the fitting text!
                    string textChunk         = textFitter.FittedText;
                    float  textChunkWidth    = textFitter.FittedWidth;
                    PointF textChunkLocation = new PointF(
                        (float)currentRow.Width,
                        (float)currentRow.Y
                        );

                    // Render the fitting text:
                    // - open the row object's local state!

                    /*
                     * NOTE: This device allows a fine-grained control over the row object's representation.
                     * It MUST be coupled with a closing statement on row object's end.
                     */
                    RowObject obj = new RowObject(
                        baseComposer.BeginLocalState(),
                        lineHeight,
                        textChunkWidth,
                        CountOccurrence(' ', textChunk)
                        );
                    currentRow.Objects.Add(obj);
                    currentRow.SpaceCount += obj.SpaceCount;
                    // - show the text chunk!
                    baseComposer.ShowText(
                        textChunk,
                        textChunkLocation
                        );
                    // - close the row object's local state!
                    baseComposer.End();

                    // Update ancillary parameters:
                    // - update row width!
                    currentRow.Width += textChunkWidth;
                    // - update cursor position!
                    index = textFitter.EndIndex;
                }

                // Evaluating trailing text...
                while (true)
                {
                    // Did we reach the text end?
                    if (index == textLength)
                    {
                        goto endTextShowing; // NOTE: I know GOTO is evil, yet in this case it's a much cleaner solution.
                    }
                    switch (text[index])
                    {
                    case '\r':
                        break;

                    case '\n':
                        // New paragraph!
                        index++;
                        ShowBreak();
                        goto endTrailParsing; // NOTE: I know GOTO is evil, yet in this case it's a much cleaner solution.

                    default:
                        // New row (within the same paragraph)!
                        EndRow(false); BeginRow();
                        goto endTrailParsing; // NOTE: I know GOTO is evil, yet in this case it's a much cleaner solution.
                    }

                    index++;
                }
                endTrailParsing :;
            }
            endTextShowing :;

            return(index);
        }
Example #6
0
        private void BuildWelcomePage(Document document, FormXObject template)
        {
            // Add welcome page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.
            SKSize pageSize = page.Size;

            PrimitiveComposer composer = new PrimitiveComposer(page);

            // Add the background template!
            composer.ShowXObject(template);
            // Wrap the content composer inside a block composer in order to achieve higher-level typographic control!

            /*
             * NOTE: BlockComposer provides block-level typographic features as text and paragraph alignment.
             * Flow-level typographic features are currently not supported: block-level typographic features
             * are the foundations upon which flow-level typographic features will sit.
             */
            BlockComposer blockComposer = new BlockComposer(composer);

            SKSize breakSize = new SKSize(0, 20); // Size of a paragraph break.
                                                  // Instantiate the page body's font!
            fonts::Font font = fonts::PdfType0Font.Load(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "lazyDog.ttf"));

            // Showing the page title...
            // Define the box frame to force the page title within!
            SKRect frame = SKRect.Create(
                20,
                150,
                (float)pageSize.Width - 90,
                (float)pageSize.Height - 250
                );

            // Begin the block!
            blockComposer.Begin(frame, XAlignmentEnum.Center, YAlignmentEnum.Top);
            // Set the font to use!
            composer.SetFont(font, 56);
            // Set the text rendering mode (outline only)!
            composer.SetTextRenderMode(TextRenderModeEnum.Stroke);
            // Show the page title!
            blockComposer.ShowText("Welcome");
            // End the block!
            blockComposer.End();

            // Showing the clown photo...
            // Instantiate a jpeg image object!
            entities::Image image         = entities::Image.Get(GetResourcePath("images" + Path.DirectorySeparatorChar + "Clown.jpg")); // Abstract image (entity).
            SKPoint         imageLocation = new SKPoint(
                blockComposer.BoundBox.Left + blockComposer.BoundBox.Width - image.Width,
                blockComposer.BoundBox.Top + blockComposer.BoundBox.Height + 25
                );

            // Show the image!
            composer.ShowXObject(
                image.ToXObject(document),
                imageLocation
                );

            SKRect descriptionFrame = SKRect.Create(
                imageLocation.X,
                imageLocation.Y + image.Height + 5,
                image.Width,
                20
                );

            frame = SKRect.Create(
                blockComposer.BoundBox.Left,
                imageLocation.Y,
                blockComposer.BoundBox.Width - image.Width - 20,
                image.Height
                );
            blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Middle);
            {
                composer.SetFont(font, 30);
                blockComposer.ShowText("This is a sample document that merely demonstrates some basic graphics features supported by PDF Clown.");
                blockComposer.ShowBreak(XAlignmentEnum.Center);
                blockComposer.ShowText("Enjoy!");
            }
            blockComposer.End();

            frame = SKRect.Create(
                blockComposer.BoundBox.Left,
                blockComposer.BoundBox.Top + blockComposer.BoundBox.Height,
                pageSize.Width - 90,
                pageSize.Height - 100 - (blockComposer.BoundBox.Top + blockComposer.BoundBox.Height)
                );
            blockComposer.Begin(frame, XAlignmentEnum.Justify, YAlignmentEnum.Bottom);
            {
                composer.SetFont(font, 14);
                blockComposer.ShowText("PS: As promised, since version 0.0.3 PDF Clown has supported");
                // Begin local state!

                /*
                 * NOTE: Local state is a powerful feature of PDF format as it lets you nest
                 * multiple graphics contexts on the graphics state stack.
                 */
                composer.BeginLocalState();
                {
                    composer.SetFillColor(TextColor_Highlight);
                    blockComposer.ShowText(" embedded latin OpenFont/TrueType and non-embedded Type 1 fonts");
                }
                composer.End();
                blockComposer.ShowText(" along with");
                composer.BeginLocalState();
                {
                    composer.SetFillColor(TextColor_Highlight);
                    blockComposer.ShowText(" paragraph construction facilities");
                }
                composer.End();
                blockComposer.ShowText(" through the BlockComposer class.");
                blockComposer.ShowBreak(breakSize);

                blockComposer.ShowText("Since version 0.0.4 the content stream stack has been completed, providing ");
                composer.BeginLocalState();
                {
                    composer.SetFillColor(TextColor_Highlight);
                    blockComposer.ShowText("fully object-oriented access to the graphics objects that describe the contents on a page.");
                }
                composer.End();
                blockComposer.ShowText(" It's a great step towards a whole bunch of possibilities, such as text extraction/replacement, that next releases will progressively exploit.");
                blockComposer.ShowBreak(breakSize);

                blockComposer.ShowText("Since version 0.0.6 it has supported ");
                composer.BeginLocalState();
                {
                    composer.SetFillColor(TextColor_Highlight);
                    blockComposer.ShowText("Unicode");
                }
                composer.End();
                blockComposer.ShowText(" for OpenFont/TrueType fonts.");
                blockComposer.ShowBreak(breakSize);

                composer.SetFont(font, 8);
                blockComposer.ShowText("This page was crafted with the nice");
                composer.BeginLocalState();
                {
                    composer.SetFont(font, 10);
                    blockComposer.ShowText(" LazyDog font");
                }
                composer.End();
                blockComposer.ShowText(" (by Paul Neave, www.neave.com)");
            }
            blockComposer.End();

            blockComposer.Begin(descriptionFrame, XAlignmentEnum.Right, YAlignmentEnum.Top);
            {
                composer.SetFont(font, 8);
                blockComposer.ShowText("Source: http://www.wikipedia.org/");
            }
            blockComposer.End();

            composer.Flush();
        }
Example #7
0
        private void BuildFreeSoftwareDefinitionPages(
            Document document,
            FormXObject template
            )
        {
            // Add page!
            Page page = new Page(document);

            document.Pages.Add(page);
            SKSize pageSize = page.Size;

            string title = "The Free Software Definition";

            // Create the article thread!
            Article article = new Article(document);
            {
                Information articleInfo = article.Information;
                articleInfo.Title  = title;
                articleInfo.Author = "Free Software Foundation, Inc.";
            }
            // Get the article beads collection to populate!
            ArticleElements articleElements = article.Elements;

            PrimitiveComposer composer = new PrimitiveComposer(page);

            // Add the background template!
            composer.ShowXObject(template);
            // Wrap the content composer inside a block composer in order to achieve higher-level typographic control!

            /*
             * NOTE: BlockComposer provides block-level typographic features as text and paragraph alignment.
             * Flow-level typographic features are currently not supported: block-level typographic features
             * are the foundations upon which flow-level typographic features will sit.
             */
            BlockComposer blockComposer = new BlockComposer(composer);

            blockComposer.Hyphenation = true;

            SKSize breakSize = new SKSize(0, 10);
            // Add the font to the document!
            fonts::Font font = fonts::PdfType0Font.Load(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "TravelingTypewriter.otf"));

            SKRect frame = SKRect.Create(
                20,
                150,
                (pageSize.Width - 90 - 20) / 2,
                pageSize.Height - 250
                );

            // Showing the 'GNU' image...
            // Instantiate a jpeg image object!
            entities::Image image = entities::Image.Get(GetResourcePath("images" + Path.DirectorySeparatorChar + "gnu.jpg")); // Abstract image (entity).

            // Show the image!
            composer.ShowXObject(
                image.ToXObject(document),
                new SKPoint(
                    (pageSize.Width - 90 - image.Width) / 2 + 20,
                    pageSize.Height - 100 - image.Height)
                );

            // Showing the title...
            blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
            composer.SetFont(font, 24);
            blockComposer.ShowText(title);
            blockComposer.End();

            // Showing the copyright note...
            frame = SKRect.Create(
                (float)blockComposer.BoundBox.Left,
                (float)blockComposer.BoundBox.Top + blockComposer.BoundBox.Height + 32,
                (float)blockComposer.BoundBox.Width,
                (float)(pageSize.Height - 100 - image.Height - 10) - (blockComposer.BoundBox.Top + blockComposer.BoundBox.Height + 32)
                );
            blockComposer.Begin(frame, XAlignmentEnum.Justify, YAlignmentEnum.Bottom);
            composer.SetFont(font, 6);
            blockComposer.ShowText("Copyright 2004, 2005, 2006 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice is preserved.");

            // Showing the body...
            blockComposer.ShowBreak(breakSize);
            composer.SetFont(font, 8.25f);
            SKRect[] frames = new SKRect[]
            {
                SKRect.Create(
                    (float)blockComposer.BoundBox.Left,
                    (float)pageSize.Height - 100 - image.Height - 10,
                    (float)blockComposer.BoundBox.Width - image.Width / 2,
                    (float)image.Height + 10
                    ),
                SKRect.Create(
                    (float)(20 + 20 + (pageSize.Width - 90 - 20) / 2),
                    150,
                    (float)(pageSize.Width - 90 - 20) / 2,
                    (float)(pageSize.Height - 100 - image.Height - 10) - 150
                    ),
                SKRect.Create(
                    (float)(20 + 20 + (pageSize.Width - 90 - 20) / 2 + image.Width / 2),
                    (float)pageSize.Height - 100 - image.Height - 10,
                    (float)blockComposer.BoundBox.Width - image.Width / 2,
                    (float)image.Height + 10
                    ),
                SKRect.Create(
                    20,
                    150,
                    (float)(pageSize.Width - 90 - 20) / 2,
                    (float)(pageSize.Height - 100) - 150
                    ),
                SKRect.Create(
                    (float)(20 + 20 + (pageSize.Width - 90 - 20) / 2),
                    150,
                    (float)(pageSize.Width - 90 - 20) / 2,
                    (float)(pageSize.Height - 100) - 150
                    )
            };
            YAlignmentEnum[] yAlignments = new YAlignmentEnum[]
            {
                YAlignmentEnum.Top,
                YAlignmentEnum.Bottom,
                YAlignmentEnum.Top,
                YAlignmentEnum.Top,
                YAlignmentEnum.Top
            };
            String[] paragraphs = new String[]
            {
                "We maintain this free software definition to show clearly what must be true about a particular software program for it to be considered free software.",
                "\"Free software\" is a matter of liberty, not price. To understand the concept, you should think of \"free\" as in \"free speech\", not as in \"free beer\".",
                "Free software is a matter of the users' freedom to run, copy, distribute, study, change and improve the software. More precisely, it refers to four kinds of freedom, for the users of the software:",
                "* The freedom to run the program, for any purpose (freedom 0).",
                "* The freedom to study how the program works, and adapt it to your needs (freedom 1). Access to the source code is a precondition for this.",
                "* The freedom to redistribute copies so you can help your neighbor (freedom 2).",
                "* The freedom to improve the program, and release your improvements to the public, so that the whole community benefits (freedom 3). Access to the source code is a precondition for this.",
                "A program is free software if users have all of these freedoms. Thus, you should be free to redistribute copies, either with or without modifications, either gratis or charging a fee for distribution, to anyone anywhere. Being free to do these things means (among other things) that you do not have to ask or pay for permission.",
                "You should also have the freedom to make modifications and use them privately in your own work or play, without even mentioning that they exist. If you do publish your changes, you should not be required to notify anyone in particular, or in any particular way.",
                "The freedom to use a program means the freedom for any kind of person or organization to use it on any kind of computer system, for any kind of overall job, and without being required to communicate subsequently with the developer or any other specific entity.",
                "The freedom to redistribute copies must include binary or executable forms of the program, as well as source code, for both modified and unmodified versions. (Distributing programs in runnable form is necessary for conveniently installable free operating systems.) It is ok if there is no way to produce a binary or executable form for a certain program (since some languages don't support that feature), but you must have the freedom to redistribute such forms should you find or develop a way to make them.",
                "In order for the freedoms to make changes, and to publish improved versions, to be meaningful, you must have access to the source code of the program. Therefore, accessibility of source code is a necessary condition for free software.",
                "In order for these freedoms to be real, they must be irrevocable as long as you do nothing wrong; if the developer of the software has the power to revoke the license, without your doing anything to give cause, the software is not free.",
                "However, certain kinds of rules about the manner of distributing free software are acceptable, when they don't conflict with the central freedoms. For example, copyleft (very simply stated) is the rule that when redistributing the program, you cannot add restrictions to deny other people the central freedoms. This rule does not conflict with the central freedoms; rather it protects them.",
                "You may have paid money to get copies of free software, or you may have obtained copies at no charge. But regardless of how you got your copies, you always have the freedom to copy and change the software, even to sell copies.",
                "\"Free software\" does not mean \"non-commercial\". A free program must be available for commercial use, commercial development, and commercial distribution. Commercial development of free software is no longer unusual; such free commercial software is very important.",
                "Rules about how to package a modified version are acceptable, if they don't substantively block your freedom to release modified versions. Rules that \"if you make the program available in this way, you must make it available in that way also\" can be acceptable too, on the same condition. (Note that such a rule still leaves you the choice of whether to publish the program or not.) It is also acceptable for the license to require that, if you have distributed a modified version and a previous developer asks for a copy of it, you must send one, or that you identify yourself on your modifications.",
                "In the GNU project, we use \"copyleft\" to protect these freedoms legally for everyone. But non-copylefted free software also exists. We believe there are important reasons why it is better to use copyleft, but if your program is non-copylefted free software, we can still use it.",
                "See Categories of Free Software for a description of how \"free software,\" \"copylefted software\" and other categories of software relate to each other.",
                "Sometimes government export control regulations and trade sanctions can constrain your freedom to distribute copies of programs internationally. Software developers do not have the power to eliminate or override these restrictions, but what they can and must do is refuse to impose them as conditions of use of the program. In this way, the restrictions will not affect activities and people outside the jurisdictions of these governments.",
                "Most free software licenses are based on copyright, and there are limits on what kinds of requirements can be imposed through copyright. If a copyright-based license respects freedom in the ways described above, it is unlikely to have some other sort of problem that we never anticipated (though this does happen occasionally). However, some free software licenses are based on contracts, and contracts can impose a much larger range of possible restrictions. That means there are many possible ways such a license could be unacceptably restrictive and non-free.",
                "We can't possibly list all the possible contract restrictions that would be unacceptable. If a contract-based license restricts the user in an unusual way that copyright-based licenses cannot, and which isn't mentioned here as legitimate, we will have to think about it, and we will probably decide it is non-free.",
                "When talking about free software, it is best to avoid using terms like \"give away\" or \"for free\", because those terms imply that the issue is about price, not freedom. Some common terms such as \"piracy\" embody opinions we hope you won't endorse. See Confusing Words and Phrases that are Worth Avoiding for a discussion of these terms. We also have a list of translations of \"free software\" into various languages.",
                "Finally, note that criteria such as those stated in this free software definition require careful thought for their interpretation. To decide whether a specific software license qualifies as a free software license, we judge it based on these criteria to determine whether it fits their spirit as well as the precise words. If a license includes unconscionable restrictions, we reject it, even if we did not anticipate the issue in these criteria. Sometimes a license requirement raises an issue that calls for extensive thought, including discussions with a lawyer, before we can decide if the requirement is acceptable. When we reach a conclusion about a new issue, we often update these criteria to make it easier to see why certain licenses do or don't qualify.",
                "If you are interested in whether a specific license qualifies as a free software license, see our list of licenses. If the license you are concerned with is not listed there, you can ask us about it by sending us email at <*****@*****.**>.",
                "If you are contemplating writing a new license, please contact the FSF by writing to that address. The proliferation of different free software licenses means increased work for users in understanding the licenses; we may be able to help you find an existing Free Software license that meets your needs.",
                "If that isn't possible, if you really need a new license, with our help you can ensure that the license really is a Free Software license and avoid various practical problems.",
                "Another group has started using the term \"open source\" to mean something close (but not identical) to \"free software\". We prefer the term \"free software\" because, once you have heard it refers to freedom rather than price, it calls to mind freedom. The word \"open\" never does that."
            };
            int paragraphIndex     = 0;
            int paragraphTextIndex = 0;
            int frameIndex         = -1;

            for (int paragraphCount = paragraphs.Length; paragraphIndex < paragraphCount; paragraphIndex++)
            {
                String paragraph = paragraphs[paragraphIndex];

                paragraphTextIndex = blockComposer.ShowText(paragraph.Substring(paragraphTextIndex)) + paragraphTextIndex;
                if (paragraphTextIndex < paragraph.Length)
                {
                    if (++frameIndex < frames.Length)
                    {
                        blockComposer.End();

                        // Add the bead to the article thread!
                        articleElements.Add(new ArticleElement(page, blockComposer.BoundBox));

                        // New page?
                        if (frameIndex == 3)
                        {
                            // Close current page!
                            composer.Flush();

                            // Create a new page!
                            document.Pages.Add(page = new Page(document));
                            composer = new PrimitiveComposer(page);
                            // Add the background template!
                            composer.ShowXObject(template);
                            blockComposer             = new BlockComposer(composer);
                            blockComposer.Hyphenation = true;
                        }

                        blockComposer.Begin(frames[frameIndex], XAlignmentEnum.Justify, yAlignments[frameIndex]);
                        composer.SetFont(font, 8.25f);

                        // Come back to complete the interrupted paragraph!
                        paragraphIndex--;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    paragraphTextIndex = 0;

                    blockComposer.ShowBreak(breakSize);
                }
            }
            blockComposer.End();

            // Add the bead to the article thread!
            articleElements.Add(new ArticleElement(page, blockComposer.BoundBox));

            blockComposer.Begin(frames[frames.Length - 1], XAlignmentEnum.Justify, YAlignmentEnum.Bottom);
            composer.SetFont(font, 6);
            blockComposer.ShowText("This article was crafted with the nice Traveling_Typewriter font (by Carl Krull, www.carlkrull.dk).");
            blockComposer.End();

            composer.Flush();
        }
Example #8
0
        /**
         * <summary>Shows text.</summary>
         * <param name="text">Text to show.</param>
         * <param name="lineAlignment">Line alignment. It can be:
         *  <list type="bullet">
         *    <item><see cref="LineAlignmentEnum"/></item>
         *    <item><see cref="Length">: arbitrary super-/sub-script, depending on whether the value is
         *    positive or not.</item>
         *  </list>
         * </param>
         * <returns>Last shown character index.</returns>
         */
        public int ShowText(
            string text,
            object lineAlignment
            )
        {
            if (currentRow == null ||
                text == null)
            {
                return(0);
            }

            ContentScanner.GraphicsState state = baseComposer.State;
            fonts::Font font       = state.Font;
            double      fontSize   = state.FontSize;
            double      lineHeight = font.GetLineHeight(fontSize);
            double      baseLine   = font.GetAscent(fontSize);

            lineAlignment = ResolveLineAlignment(lineAlignment);

            TextFitter textFitter = new TextFitter(
                text,
                0,
                font,
                fontSize,
                hyphenation,
                hyphenationCharacter
                );
            int textLength = text.Length;
            int index      = 0;

            while (true)
            {
                if (currentRow.Width == 0) // Current row has just begun.
                {
                    // Removing leading space...
                    while (true)
                    {
                        if (index == textLength) // Text end reached.
                        {
                            goto endTextShowing;
                        }
                        else if (text[index] != ' ') // No more leading spaces.
                        {
                            break;
                        }

                        index++;
                    }
                }

                if (OperationUtils.Compare(currentRow.Y + lineHeight, frame.Height) == 1) // Text's height exceeds block's remaining vertical space.
                {
                    // Terminate the current row and exit!
                    EndRow(false);
                    goto endTextShowing;
                }

                // Does the text fit?
                if (textFitter.Fit(
                        index,
                        frame.Width - currentRow.Width, // Remaining row width.
                        currentRow.SpaceCount == 0
                        ))
                {
                    // Get the fitting text!
                    string textChunk         = textFitter.FittedText;
                    double textChunkWidth    = textFitter.FittedWidth;
                    PointF textChunkLocation = new PointF(
                        (float)currentRow.Width,
                        (float)currentRow.Y
                        );

                    // Insert the fitting text!
                    RowObject obj;
                    {
                        obj = new RowObject(
                            RowObject.TypeEnum.Text,
                            baseComposer.BeginLocalState(), // Opens the row object's local state.
                            lineHeight,
                            textChunkWidth,
                            CountOccurrence(' ', textChunk),
                            lineAlignment,
                            baseLine
                            );
                        baseComposer.ShowText(textChunk, textChunkLocation);
                        baseComposer.End(); // Closes the row object's local state.
                    }
                    AddRowObject(obj, lineAlignment);

                    index = textFitter.EndIndex;
                }

                // Evaluating trailing text...
                while (true)
                {
                    if (index == textLength) // Text end reached.
                    {
                        goto endTextShowing;
                    }

                    switch (text[index])
                    {
                    case '\r':
                        break;

                    case '\n':
                        // New paragraph!
                        index++;
                        ShowBreak();
                        goto endTrailParsing;

                    default:
                        // New row (within the same paragraph)!
                        EndRow(false);
                        BeginRow();
                        goto endTrailParsing;
                    }

                    index++;
                }
                endTrailParsing :;
            }
            endTextShowing :;
            if (index >= 0 &&
                lineAlignment.Equals(LineAlignmentEnum.BaseLine))
            {
                lastFontSize = fontSize;
            }

            return(index);
        }
Example #9
0
        private void BuildTextBlockPage4(Document document)
        {
            // 1. Add the page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            SKSize pageSize = page.Size;

            // 2. Create a content composer for the page!
            PrimitiveComposer composer = new PrimitiveComposer(page);

            // 3. Drawing the page contents...
            fonts::Font   mainFont      = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Courier, true, false);
            int           stepCount     = 5;
            int           step          = (int)pageSize.Height / (stepCount + 1);
            BlockComposer blockComposer = new BlockComposer(composer);

            {
                blockComposer.Begin(
                    SKRect.Create(
                        30,
                        0,
                        pageSize.Width - 60,
                        step * .8f
                        ),
                    XAlignmentEnum.Center,
                    YAlignmentEnum.Middle
                    );
                composer.SetFont(mainFont, 32);
                blockComposer.ShowText("Unspaced block");
                blockComposer.End();
            }

            // Drawing the text block...
            {
                fonts::Font sampleFont = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Times, false, false);
                composer.SetFont(sampleFont, 15);

                float topMargin = 100;
                float boxMargin = 30;
                float boxWidth  = pageSize.Width - boxMargin * 2;
                float boxHeight = (pageSize.Height - topMargin - boxMargin - boxMargin) / 2;
                {
                    SKRect frame = SKRect.Create(
                        boxMargin,
                        topMargin,
                        boxWidth,
                        boxHeight
                        );
                    blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
                    // Add text until the frame area is completely filled!
                    while (blockComposer.ShowText("DemonstratingHowUnspacedTextIsManagedInCaseOfInsertionInADelimitedPageAreaThroughBlockComposerClass.") > 0)
                    {
                        ;
                    }
                    blockComposer.End();

                    composer.BeginLocalState();
                    {
                        composer.SetLineWidth(0.2);
                        composer.SetLineDash(new LineDash(new float[] { 5 }, 5));
                        composer.DrawRectangle(frame);
                        composer.Stroke();
                    }
                    composer.End();
                }
                {
                    SKRect frame = SKRect.Create(
                        boxMargin,
                        topMargin + boxHeight + boxMargin,
                        boxWidth,
                        boxHeight
                        );
                    blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
                    // Add text until the frame area is completely filled!
                    while (blockComposer.ShowText(" DemonstratingHowUnspacedTextWithLeadingSpaceIsManagedInCaseOfInsertionInADelimitedPageAreaThroughBlockComposerClass.") > 0)
                    {
                        ;
                    }
                    blockComposer.End();

                    composer.BeginLocalState();
                    {
                        composer.SetLineWidth(0.2);
                        composer.SetLineDash(new LineDash(new float[] { 5 }, 5));
                        composer.DrawRectangle(frame);
                        composer.Stroke();
                    }
                    composer.End();
                }
            }

            // 4. Flush the contents into the page!
            composer.Flush();
        }
Example #10
0
        /**
         * <summary>Populates a PDF file with contents.</summary>
         */
        private void Populate(Document document)
        {
            // 1. Add the page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            // 2.1. Create a content composer for the page!
            PrimitiveComposer composer = new PrimitiveComposer(page);

            // 2.2. Create a block composer!
            BlockComposer blockComposer = new BlockComposer(composer);

            // 3. Inserting contents...
            // Define the font to use!
            fonts::Font font = fonts::Font.Get(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "GenR102.TTF"));
            // Define the paragraph break size!
            var breakSize = new SKSize(0, 10);

            // Define the text to show!
            string[] titles = new string[]
            {
                "ΑΡΘΡΟ 1",
                "ASARIYA SINTE (1)",
                "Article 1",
                "Article premier",
                "Статья 1",
                "Artículo 1",
                "Artikel 1",
                "Madde 1",
                "Artikel 1",
                "Articolo 1",
                "Artykuł 1",
                "Bend 1",
                "Abala kìíní."
            };
            string[] bodies = new string[]
            {
                "'Ολοι οι άνθρωποι γεννιούνται ελεύθεροι και ίσοι στην αξιοπρέπεια και τα δικαιώματα. Είναι προικισμένοι με λογική και συνείδηση, και οφείλουν να συμπεριφέρονται μεταξύ τους με πνεύμα αδελφοσύνης.",
                "Aduniya kuna n gu ibuna damayo hɛi nɔ dei-dei nn daama nna n burucinitɛrɛ fɔ, n lasabu nna laakari ya nam nn mɔ huro cɛrɛ kuna nyanze tɛrɛ bɔŋɔɔ.",
                "All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.",
                "Tous les êtres humains naissent libres et égaux en dignité et en droits. Ils sont doués de raison et de conscience et doivent agir les uns envers les autres dans un esprit de fraternité.",
                "Все люди рождаются свободными и равными в своем достоинстве и правах. Они наделены разумом и совестью и должны поступать в отношении друг друга в духе братства.",
                "Todos los seres humanos nacen libres e iguales en dignidad y derechos y, dotados como están de razón y conciencia, deben comportarse fraternalmente los unos con los otros.",
                "Alle Menschen sind frei und gleich an Würde und Rechten geboren. Sie sind mit Vernunft und Gewissen begabt und sollen einander im Geist der Brüderlichkeit begegnen.",
                "Bütün insanlar hür, haysiyet ve haklar bakımından eşit doğarlar. Akıl ve vicdana sahiptirler ve birbirlerine karşı kardeşlik zihniyeti ile hareket etmelidirler.",
                "Alla människor är födda fria och lika i värde och rättigheter. De har utrustats med förnuft och samvete och bör handla gentemot varandra i en anda av gemenskap.",
                "Tutti gli esseri umani nascono liberi ed eguali in dignità e diritti. Essi sono dotati di ragione e di coscienza e devono agire gli uni verso gli altri in spirito di fratellanza.",
                "Wszyscy ludzie rodzą się wolni i równi pod względem swej godności i swych praw. Są oni obdarzeni rozumem i sumieniem i powinni postępować wobec innych w duchu braterstwa.",
                "Hemû mirov azad û di weqar û mafan de wekhev tên dinyayê. Ew xwedî hiş û şuûr in û divê li hember hev bi zihniyeteke bratiyê bilivin.",
                "Gbogbo ènìyàn ni a bí ní òmìnira; iyì àti è̟tó̟ kò̟ò̟kan sì dó̟gba. Wó̟n ní è̟bùn ti làákàyè àti ti è̟rí-o̟kàn, ó sì ye̟ kí wo̟n ó máa hùwà sí ara wo̟n gé̟gé̟ bí o̟mo̟ ìyá."
            };
            string[] sources = new string[]
            {
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=grk",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=den",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=eng",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=frn",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=rus",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=spn",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=ger",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=trk",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=swd",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=itn",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=pql",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=kdb1",
                "http://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=yor"
            };
            // Begin the content block!
            blockComposer.Begin(
                SKRect.Create(Margin, Margin, page.Size.Width - Margin * 2, page.Size.Height - Margin * 2),
                XAlignmentEnum.Justify,
                YAlignmentEnum.Top);
            for (int index = 0, length = titles.Length; index < length; index++)
            {
                composer.SetFont(font, 12);
                blockComposer.ShowText(titles[index]);
                blockComposer.ShowBreak();

                composer.SetFont(font, 11);
                blockComposer.ShowText(bodies[index]);
                blockComposer.ShowBreak(XAlignmentEnum.Right);

                composer.SetFont(font, 8);
                blockComposer.ShowText("[Source: " + sources[index] + "]");
                blockComposer.ShowBreak(breakSize, XAlignmentEnum.Justify);
            }
            // End the content block!
            blockComposer.End();

            // 4. Flush the contents into the page!
            composer.Flush();
        }
Example #11
0
        private void BuildTextBlockPage3(Document document)
        {
            // 1. Add the page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            SKSize pageSize = page.Size;

            // 2. Create a content composer for the page!
            PrimitiveComposer composer = new PrimitiveComposer(page);

            // 3. Drawing the page contents...
            fonts::Font mainFont  = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Courier, true, false);
            int         stepCount = 5;
            int         step      = (int)(pageSize.Height) / (stepCount + 1);

            // 3.1. Drawing the page title...
            BlockComposer blockComposer = new BlockComposer(composer);
            {
                blockComposer.Begin(
                    SKRect.Create(
                        30,
                        0,
                        pageSize.Width - 60,
                        step * .8f
                        ),
                    XAlignmentEnum.Center,
                    YAlignmentEnum.Middle
                    );
                composer.SetFont(mainFont, 32);
                blockComposer.ShowText("Block line space");
                blockComposer.End();
            }

            // 3.2. Drawing the text blocks...
            fonts::Font sampleFont = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Times, false, false);
            int         x          = 30;
            int         y          = (int)(step * 1.1);

            blockComposer.LineSpace.UnitMode = Length.UnitModeEnum.Relative;
            for (int index = 0; index < stepCount; index++)
            {
                float relativeLineSpace = 0.5f * index;
                blockComposer.LineSpace.Value = relativeLineSpace;

                composer.SetFont(mainFont, 12);
                composer.ShowText(
                    relativeLineSpace + ":",
                    new SKPoint(x, y),
                    XAlignmentEnum.Left,
                    YAlignmentEnum.Middle,
                    0
                    );

                composer.SetFont(sampleFont, 10);
                SKRect frame = SKRect.Create(150, y - step * .4f, 350, step * .9f);
                blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
                blockComposer.ShowText("Demonstrating how to set the block line space. Line space can be expressed either as an absolute value (in user-space units) or as a relative one (floating-point ratio); in the latter case the base value is represented by the current font's line height (so that, for example, 2 means \"a line space that's twice as the line height\").");
                blockComposer.End();

                composer.BeginLocalState();
                {
                    composer.SetLineWidth(0.2);
                    composer.SetLineDash(new LineDash(new float[] { 5 }, 5));
                    composer.DrawRectangle(frame);
                    composer.Stroke();
                }
                composer.End();

                y += step;
            }

            // 4. Flush the contents into the page!
            composer.Flush();
        }
Example #12
0
        private void BuildTextBlockPage2(Document document)
        {
            // 1. Add the page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            SKSize pageSize = page.Size;

            // 2. Create a content composer for the page!
            PrimitiveComposer composer = new PrimitiveComposer(page);

            // 3. Drawing the page contents...
            fonts::Font   mainFont      = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Courier, true, false);
            int           stepCount     = 5;
            int           step          = (int)(pageSize.Height) / (stepCount + 1);
            BlockComposer blockComposer = new BlockComposer(composer);

            {
                blockComposer.Begin(
                    SKRect.Create(30, 0, pageSize.Width - 60, step * .8f),
                    XAlignmentEnum.Center,
                    YAlignmentEnum.Middle
                    );
                composer.SetFont(mainFont, 32);
                blockComposer.ShowText("Block line alignment");
                blockComposer.End();
            }

            // Drawing the text block...
            {
                fonts::Font       sampleFont         = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Times, false, false);
                entities::Image   sampleImage        = entities::Image.Get(GetResourcePath("images" + System.IO.Path.DirectorySeparatorChar + "gnu.jpg"));
                xObjects::XObject sampleImageXObject = sampleImage.ToXObject(document);

                IList <LineAlignmentEnum> lineAlignments = new List <LineAlignmentEnum>((LineAlignmentEnum[])Enum.GetValues(typeof(LineAlignmentEnum)));
                float frameHeight = (pageSize.Height - 130 - 5 * lineAlignments.Count * 2) / (lineAlignments.Count * 2);
                float frameWidth  = (pageSize.Width - 60 - 5 * lineAlignments.Count) / lineAlignments.Count;
                int   imageSize   = 7;
                for (int index = 0, length = lineAlignments.Count; index < length; index++)
                {
                    LineAlignmentEnum lineAlignment = lineAlignments[index];

                    for (int imageIndex = 0, imageLength = lineAlignments.Count; imageIndex < imageLength; imageIndex++)
                    {
                        LineAlignmentEnum imageAlignment = lineAlignments[imageIndex];

                        for (int index2 = 0, length2 = 2; index2 < length2; index2++)
                        {
                            SKRect frame = SKRect.Create(
                                30 + (frameWidth + 5) * imageIndex,
                                100 + (frameHeight + 5) * (index * 2 + index2),
                                frameWidth,
                                frameHeight
                                );

                            blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
                            {
                                composer.SetFont(mainFont, 3);
                                blockComposer.ShowText("Text: " + lineAlignment);
                                blockComposer.ShowBreak();
                                blockComposer.ShowText("Image: " + imageAlignment);
                            }
                            blockComposer.End();

                            blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Middle);
                            {
                                composer.SetFont(sampleFont, 3);
                                blockComposer.ShowText("Previous row boundary.");
                                blockComposer.ShowBreak();
                                composer.SetFont(sampleFont, index2 == 0 ? 3 : 6);
                                blockComposer.ShowText("Alignment:");
                                composer.SetFont(sampleFont, index2 == 0 ? 6 : 3);
                                blockComposer.ShowText(" aligned to " + lineAlignment + " ", lineAlignment);
                                blockComposer.ShowXObject(sampleImageXObject, new SKSize(imageSize, imageSize), imageAlignment);
                                blockComposer.ShowBreak();
                                composer.SetFont(sampleFont, 3);
                                blockComposer.ShowText("Next row boundary.");
                            }
                            blockComposer.End();

                            composer.BeginLocalState();
                            {
                                composer.SetLineWidth(0.1f);
                                composer.SetLineDash(new LineDash(new float[] { 1, 4 }, 4));
                                composer.DrawRectangle(blockComposer.Frame);
                                composer.Stroke();
                            }
                            composer.End();

                            composer.BeginLocalState();
                            {
                                composer.SetLineWidth(0.1f);
                                composer.SetLineDash(new LineDash(new float[] { 1 }, 1));
                                composer.DrawRectangle(blockComposer.BoundBox);
                                composer.Stroke();
                            }
                            composer.End();
                        }
                    }
                }
            }

            // 4. Flush the contents into the page!
            composer.Flush();
        }
Example #13
0
        private void BuildTextBlockPage(Document document)
        {
            // 1. Add the page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            SKSize pageSize = page.Size;

            // 2. Create a content composer for the page!
            PrimitiveComposer composer = new PrimitiveComposer(page);

            // 3. Drawing the page contents...
            fonts::Font mainFont = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Courier, true, false);
            int         step;
            {
                XAlignmentEnum[] xAlignments = (XAlignmentEnum[])Enum.GetValues(typeof(XAlignmentEnum));
                YAlignmentEnum[] yAlignments = (YAlignmentEnum[])Enum.GetValues(typeof(YAlignmentEnum));
                step = (int)(pageSize.Height) / (xAlignments.Length * yAlignments.Length + 1);
            }
            BlockComposer blockComposer = new BlockComposer(composer);
            {
                blockComposer.Begin(
                    SKRect.Create(
                        30,
                        0,
                        pageSize.Width - 60,
                        step * .8f
                        ),
                    XAlignmentEnum.Center,
                    YAlignmentEnum.Middle
                    );
                composer.SetFont(mainFont, 32);
                blockComposer.ShowText("Block alignment");
                blockComposer.End();
            }

            // Drawing the text blocks...
            fonts::Font sampleFont = fonts::PdfType1Font.Load(document, fonts::PdfType1Font.FamilyEnum.Times, false, false);
            int         x          = 30;
            int         y          = (int)(step * 1.2);

            foreach (XAlignmentEnum xAlignment in (XAlignmentEnum[])Enum.GetValues(typeof(XAlignmentEnum)))
            {
                foreach (YAlignmentEnum yAlignment in (YAlignmentEnum[])Enum.GetValues(typeof(YAlignmentEnum)))
                {
                    composer.SetFont(mainFont, 12);
                    composer.ShowText(
                        xAlignment + " " + yAlignment + ":",
                        new SKPoint(x, y),
                        XAlignmentEnum.Left,
                        YAlignmentEnum.Middle,
                        0
                        );

                    composer.SetFont(sampleFont, 12);
                    for (int index = 0; index < 2; index++)
                    {
                        int frameX;
                        switch (index)
                        {
                        case 0:
                            frameX = 150;
                            blockComposer.Hyphenation = false;
                            break;

                        case 1:
                            frameX = 360;
                            blockComposer.Hyphenation = true;
                            break;

                        default:
                            throw new Exception();
                        }

                        SKRect frame = SKRect.Create(
                            frameX,
                            y - step * .4f,
                            200,
                            step * .8f
                            );
                        blockComposer.Begin(frame, xAlignment, yAlignment);
                        blockComposer.ShowText(
                            "Demonstrating how to constrain text inside a page area. See the other code samples for more usage tips."
                            );
                        blockComposer.End();

                        composer.BeginLocalState();
                        composer.SetLineWidth(0.2f);
                        composer.SetLineDash(new LineDash(new float[] { 5 }, 5));
                        composer.DrawRectangle(frame);
                        composer.Stroke();
                        composer.End();
                    }

                    y += step;
                }
            }

            // 4. Flush the contents into the page!
            composer.Flush();
        }
Example #14
0
        private void Build(Document document)
        {
            // Add a page to the document!
            Page page = new Page(document); // Instantiates the page inside the document context.

            document.Pages.Add(page);       // Puts the page in the pages collection.

            SKSize pageSize = page.Size;

            // Create a content composer for the content stream!

            /*
             * NOTE: There are several ways to add contents to a content stream:
             * - adding content objects directly to the Contents collection;
             * - adding content objects through a ContentScanner instance;
             * - invoking basic drawing functions through a PrimitiveComposer instance;
             * - invoking advanced static-positioning functions through a BlockComposer instance;
             * - invoking advanced dynamic-positioning functions through a FlowComposer instance (currently not implemented yet).
             */
            PrimitiveComposer composer = new PrimitiveComposer(page);
            // Wrap the content composer within a block filter!

            /*
             * NOTE: The block filter is a basic typesetter. It exposes higher-level graphical
             * functionalities (horizontal/vertical alignment, indentation, paragraph composition etc.)
             * leveraging the content composer primitives.
             * It's important to note that this is just an intermediate abstraction layer of the typesetting
             * stack: further abstract levels could sit upon it, allowing the convenient treatment of
             * typographic entities like titles, paragraphs, columns, tables, headers, footers etc.
             * When such further abstract levels are available, the final user (developer of consuming
             * applications) won't care any more of the details you can see here in the following code lines
             * (such as bothering to select the first-letter font...).
             */
            BlockComposer blockComposer = new BlockComposer(composer);

            composer.BeginLocalState();
            // Define the block frame that will constrain our contents on the page canvas!
            SKRect frame = SKRect.Create(
                Margin_X,
                Margin_Y,
                (float)pageSize.Width - Margin_X * 2,
                (float)pageSize.Height - Margin_Y * 2
                );

            // Begin the title block!
            blockComposer.Begin(frame, XAlignmentEnum.Left, YAlignmentEnum.Top);
            fonts::Font decorativeFont = fonts::Font.Get(
                document,
                GetResourcePath("fonts" + Path.DirectorySeparatorChar + "Ruritania-Outline.ttf")
                );

            composer.SetFont(decorativeFont, 56);
            blockComposer.ShowText("Chapter 1");
            blockComposer.ShowBreak();
            composer.SetFont(decorativeFont, 32);
            blockComposer.ShowText("Down the Rabbit-Hole");
            // End the title block!
            blockComposer.End();
            // Update the block frame in order to begin after the title!
            frame = SKRect.Create(
                (float)blockComposer.BoundBox.Left,
                (float)blockComposer.BoundBox.Top + blockComposer.BoundBox.Height,
                (float)blockComposer.BoundBox.Width,
                (float)pageSize.Height - Margin_Y - (blockComposer.BoundBox.Top + blockComposer.BoundBox.Height)
                );
            // Begin the body block!
            blockComposer.Begin(frame, XAlignmentEnum.Justify, YAlignmentEnum.Bottom);
            fonts::Font bodyFont = fonts::Font.Get(
                document,
                GetResourcePath("fonts" + Path.DirectorySeparatorChar + "TravelingTypewriter.otf")
                );

            composer.SetFont(bodyFont, 14);
            composer.BeginLocalState();
            composer.SetFont(decorativeFont, 28);
            blockComposer.ShowText("A");
            composer.End();
            blockComposer.ShowText("lice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'");
            // Define new-paragraph first-line offset!
            SKSize breakSize = new SKSize(24, 8); // Indentation (24pt) and top margin (8pt).

            // Begin a new paragraph!
            blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.");
            // Begin a new paragraph!
            blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("There was nothing so VERY remarkable in that; nor did Alice think it so VERY much out of the way to hear the Rabbit say to itself, 'Oh dear! Oh dear! I shall be late!' (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT- POCKET, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.");
            // End the body block!
            blockComposer.End();
            composer.End();

            composer.BeginLocalState();
            composer.Rotate(
                90,
                new SKPoint(
                    pageSize.Width - 50,
                    pageSize.Height - 25
                    )
                );
            blockComposer = new BlockComposer(composer);
            blockComposer.Begin(
                SKRect.Create(0, 0, 300, 50),
                XAlignmentEnum.Left,
                YAlignmentEnum.Middle
                );
            composer.SetFont(bodyFont, 8);
            blockComposer.ShowText("Generated by PDF Clown on " + System.DateTime.Now);
            blockComposer.ShowBreak();
            blockComposer.ShowText("For more info, visit http://www.pdfclown.org");
            blockComposer.End();
            composer.End();

            // Flush the contents into the page!
            composer.Flush();
        }
Example #15
0
        private void RefreshAppearance(
            )
        {
            Widget      widget = Widgets[0];
            FormXObject normalAppearance;
            {
                AppearanceStates normalAppearances = widget.Appearance.Normal;
                normalAppearance = normalAppearances[null];
                if (normalAppearance == null)
                {
                    normalAppearances[null] = normalAppearance = new FormXObject(Document, widget.Box.Size);
                }
            }
            PdfName fontName = null;
            double  fontSize = 0;
            {
                PdfString defaultAppearanceState = DefaultAppearanceState;
                if (defaultAppearanceState == null)
                {
                    // Retrieving the font to define the default appearance...
                    fonts::Font defaultFont     = null;
                    PdfName     defaultFontName = null;
                    {
                        // Field fonts.
                        FontResources normalAppearanceFonts = normalAppearance.Resources.Fonts;
                        foreach (KeyValuePair <PdfName, fonts::Font> entry in normalAppearanceFonts)
                        {
                            if (!entry.Value.Symbolic)
                            {
                                defaultFont     = entry.Value;
                                defaultFontName = entry.Key;
                                break;
                            }
                        }
                        if (defaultFontName == null)
                        {
                            // Common fonts.
                            FontResources formFonts = Document.Form.Resources.Fonts;
                            foreach (KeyValuePair <PdfName, fonts::Font> entry in formFonts)
                            {
                                if (!entry.Value.Symbolic)
                                {
                                    defaultFont     = entry.Value;
                                    defaultFontName = entry.Key;
                                    break;
                                }
                            }
                            if (defaultFontName == null)
                            {
                                //TODO:manage name collision!
                                formFonts[
                                    defaultFontName = new PdfName("default")
                                ] = defaultFont = new fonts::StandardType1Font(
                                    Document,
                                    fonts::StandardType1Font.FamilyEnum.Helvetica,
                                    false,
                                    false
                                    );
                            }
                            normalAppearanceFonts[defaultFontName] = defaultFont;
                        }
                    }
                    bytes::Buffer buffer = new bytes::Buffer();
                    new SetFont(defaultFontName, IsMultiline ? 10 : 0).WriteTo(buffer, Document);
                    widget.BaseDataObject[PdfName.DA] = defaultAppearanceState = new PdfString(buffer.ToByteArray());
                }

                // Retrieving the font to use...
                ContentParser parser = new ContentParser(defaultAppearanceState.ToByteArray());
                foreach (ContentObject content in parser.ParseContentObjects())
                {
                    if (content is SetFont)
                    {
                        SetFont setFontOperation = (SetFont)content;
                        fontName = setFontOperation.Name;
                        fontSize = setFontOperation.Size;
                        break;
                    }
                }
                normalAppearance.Resources.Fonts[fontName] = Document.Form.Resources.Fonts[fontName];
            }

            // Refreshing the field appearance...

            /*
             * TODO: resources MUST be resolved both through the apperance stream resource dictionary and
             * from the DR-entry acroform resource dictionary
             */
            PrimitiveComposer baseComposer = new PrimitiveComposer(normalAppearance);
            BlockComposer     composer     = new BlockComposer(baseComposer);
            ContentScanner    currentLevel = composer.Scanner;
            bool textShown = false;

            while (currentLevel != null)
            {
                if (!currentLevel.MoveNext())
                {
                    currentLevel = currentLevel.ParentLevel;
                    continue;
                }

                ContentObject content = currentLevel.Current;
                if (content is MarkedContent)
                {
                    MarkedContent markedContent = (MarkedContent)content;
                    if (PdfName.Tx.Equals(((BeginMarkedContent)markedContent.Header).Tag))
                    {
                        // Remove old text representation!
                        markedContent.Objects.Clear();
                        // Add new text representation!
                        baseComposer.Scanner = currentLevel.ChildLevel; // Ensures the composer places new contents within the marked content block.
                        ShowText(composer, fontName, fontSize);
                        textShown = true;
                    }
                }
                else if (content is Text)
                {
                    currentLevel.Remove();
                }
                else if (currentLevel.ChildLevel != null)
                {
                    currentLevel = currentLevel.ChildLevel;
                }
            }
            if (!textShown)
            {
                baseComposer.BeginMarkedContent(PdfName.Tx);
                ShowText(composer, fontName, fontSize);
                baseComposer.End();
            }
            baseComposer.Flush();
        }