Example #1
0
        public void PrintCreditos()
        {
            BlockComposer bComp = new BlockComposer(_Composer);
            RectangleF rect = _Danfe.InnerRect;

            rect.Y = rect.Bottom + Utils.Mm2Pu(0.5F);
            rect.Height = _Danfe.Size.Height - rect.Y;

            _Composer.SetFont(_Danfe.Font, 6);
            bComp.SafeBegin(rect, XAlignmentEnum.Right, YAlignmentEnum.Top);
            bComp.ShowText("Gerado com DanfeSharp");
            bComp.End();
        }
        public void PrintCabecalhos(PrimitiveComposer composer)
        {
            BlockComposer bComp = new BlockComposer(composer);
            composer.SetFont(_Documento.FontBold, 5);

            for (int i = 0; i < _Colunas.Length; i++)
            {
                RectangleF r = _Colunas[i].Retangulo;
                r.Height = AlturaCabecalhoTabela;
                bComp.SafeBegin(r.GetPaddedRectangle(Margem), _Colunas[i].AlinhamentoHorizontal, YAlignmentEnum.Middle);
                bComp.ShowText(_Colunas[i].Cabecalho.ToUpper());
                bComp.End();

                composer.SafeDrawRectangle(r);
            }
        }
Example #3
0
        private void Populate(
            Document document
            )
        {
            Page page = new Page(document);
              document.Pages.Add(page);
              SizeF pageSize = page.Size;

              PrimitiveComposer composer = new PrimitiveComposer(page);
              {
            BlockComposer blockComposer = new BlockComposer(composer);
            blockComposer.Hyphenation = true;
            blockComposer.Begin(
              new RectangleF(
            Margin,
            Margin,
            (float)pageSize.Width - Margin * 2,
            (float)pageSize.Height - Margin * 2
            ),
              XAlignmentEnum.Justify,
              YAlignmentEnum.Top
              );
            StandardType1Font bodyFont = new StandardType1Font(
              document,
              StandardType1Font.FamilyEnum.Courier,
              true,
              false
              );
            composer.SetFont(bodyFont,32);
            blockComposer.ShowText("Inline image sample"); blockComposer.ShowBreak();
            composer.SetFont(bodyFont,16);
            blockComposer.ShowText("Showing the GNU logo as an inline image within the page content stream.");
            blockComposer.End();
              }
              // Showing the 'GNU' image...
              {
            // Instantiate a jpeg image object!
            entities::Image image = entities::Image.Get(GetResourcePath("images" + Path.DirectorySeparatorChar + "gnu.jpg")); // Abstract image (entity).
            // Set the position of the image in the page!
            composer.ApplyMatrix(200,0,0,200,(pageSize.Width-200)/2,(pageSize.Height-200)/2);
            // Show the image!
            image.ToInlineObject(composer); // Transforms the image entity into an inline image within the page.
              }
              composer.Flush();
        }
Example #4
0
        protected override void ToXObjectInternal(PrimitiveComposer comp)
        {
            var duplicatas = Danfe.Model.Duplicatas;

            BlockComposer bComp = new BlockComposer(comp);

            RectangleF r1 = InternalRectangle;
            r1.Height = RetanguloH;

            RectangleF[] colunas = r1.SplitRectangle(Colunas);
            int colunaIndex = 0;

            for (int i = 0; i < duplicatas.Count; i++)
            {

                if (i > 0 && i % Colunas == 0)
                {
                    colunaIndex = 0;

                    for (int i2 = 0; i2 < Colunas; i2++)
                    {
                        colunas[i2].Y += RetanguloH;
                    }
                }

                var duplicata = duplicatas[i];
                RectangleF pRet = colunas[colunaIndex].GetPaddedRectangleMm(1);
                comp.SetFont(Danfe.Font, 6);
                bComp.SafeBegin(pRet, XAlignmentEnum.Left, YAlignmentEnum.Middle);
                bComp.ShowText("Número:\nVenc.:\nValor:\n");
                bComp.End();

                comp.SetFont(Danfe.FontBold, 6);

                bComp.SafeBegin(pRet, XAlignmentEnum.Right, YAlignmentEnum.Middle);
                bComp.ShowText(String.Format("{0}\n{1}\n{2}\n", duplicata.Numero, duplicata.Vecimento.Formatar(), duplicata.Valor.Formatar()));
                bComp.End();

                comp.SafeDrawRectangle(colunas[colunaIndex]);

                colunaIndex++;
            }

            comp.Stroke();
        }
Example #5
0
        private void ShowText(
      BlockComposer composer,
      PdfName fontName,
      double fontSize
      )
        {
            PrimitiveComposer baseComposer = composer.BaseComposer;
              ContentScanner scanner = baseComposer.Scanner;
              RectangleF textBox = scanner.ContentContext.Box;
              if(scanner.State.Font == null)
              {
            /*
              NOTE: A zero value for size means that the font is to be auto-sized: its size is computed as
              a function of the height of the annotation rectangle.
            */
            if(fontSize == 0)
            {fontSize = textBox.Height * 0.65;}
            baseComposer.SetFont(fontName, fontSize);
              }

              string text = (string)Value;

              FlagsEnum flags = Flags;
              if((flags & FlagsEnum.Comb) == FlagsEnum.Comb
            && (flags & FlagsEnum.FileSelect) == 0
            && (flags & FlagsEnum.Multiline) == 0
            && (flags & FlagsEnum.Password) == 0)
              {
            int maxLength = MaxLength;
            if(maxLength > 0)
            {
              textBox.Width /= maxLength;
              for(int index = 0, length = text.Length; index < length; index++)
              {
            composer.Begin(
              textBox,
              XAlignmentEnum.Center,
              YAlignmentEnum.Middle
              );
            composer.ShowText(text[index].ToString());
            composer.End();
            textBox.X += textBox.Width;
              }
              return;
            }
              }

              textBox.X += 2;
              textBox.Width -= 4;
              YAlignmentEnum yAlignment;
              if((flags & FlagsEnum.Multiline) == FlagsEnum.Multiline)
              {
            yAlignment = YAlignmentEnum.Top;
            textBox.Y += (float)(fontSize * .35);
            textBox.Height -= (float)(fontSize * .7);
              }
              else
              {
            yAlignment = YAlignmentEnum.Middle;
              }
              composer.Begin(
            textBox,
            Justification.ToXAlignment(),
            yAlignment
            );
              composer.ShowText(text);
              composer.End();
        }
Example #6
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();
        }
Example #7
0
        private void BuildLegend(
            PrimitiveComposer composer,
            string[] steps,
            colorSpaces::Color[] colors,
            SizeF pageSize
            )
        {
            float maxCtmInversionApproximation;
              {
            float[] ctmInversionApproximations = new float[6];
            {
              float[] initialCtmValues, finalCtmValues;
              {
            ContentScanner.GraphicsState state = composer.Scanner.State;
            initialCtmValues = state.GetInitialCtm().Elements;
            finalCtmValues = state.Ctm.Elements;
              }
              for(
            int index = 0,
              length = finalCtmValues.Length;
            index < length;
            index++
            )
              {ctmInversionApproximations[index] = Math.Abs(finalCtmValues[index]) - initialCtmValues[index];}
            }
            maxCtmInversionApproximation = Max(ctmInversionApproximations);
              }

              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.LineSpace = new Length(.25, Length.UnitModeEnum.Relative);

              composer.BeginLocalState();
              composer.SetFillColor(
            new colorSpaces::DeviceRGBColor(115 / 255d, 164 / 255d, 232 / 255d)
            );
              RectangleF frame = new RectangleF(
            18,
            18,
            pageSize.Width * .5f,
            pageSize.Height * .5f
            );
              blockComposer.Begin(frame,XAlignmentEnum.Left,YAlignmentEnum.Top);
              composer.SetFont(ResourceName_DefaultFont,24);
              blockComposer.ShowText("Page coordinates sample");
              SizeF breakSize = new SizeF(0,8);
              blockComposer.ShowBreak(breakSize);
              composer.SetFont(ResourceName_DefaultFont,8);
              blockComposer.ShowText(
            "This sample shows the effects of the manipulation of the CTM (Current Transformation Matrix), "
              + "that is the mathematical device which affects the page coordinate system used to place "
              + "graphic contents onto the canvas."
            );
              blockComposer.ShowBreak(breakSize);
              blockComposer.ShowText(
            "The following steps represent the operations applied to this page's CTM in order to alter it. "
              + "Each step writes the word \"Step\" at the lower-left corner of the current page frame:"
            );
              blockComposer.ShowBreak(breakSize);
              for(int i = 0; i < steps.Length; i++)
              {
            composer.SetFillColor(colors[i]);
            blockComposer.ShowText("Step " + i + ")");
            composer.SetFillColor(
              new colorSpaces::DeviceRGBColor(115 / 255d, 164 / 255d, 232 / 255d)
              );
            blockComposer.ShowText(" " + steps[i]);
            blockComposer.ShowBreak(breakSize);
              }
              blockComposer.ShowText("Note that the approximation (" + maxCtmInversionApproximation + ") of the CTM components at step 4 is due to floating point precision limits; their exact values should be 1.0, 0.0, 0.0, 1.0, 0.0, 0.0.");
              blockComposer.End();
              composer.End();
        }
Example #8
0
        /**
          <summary>Populates a PDF file with contents.</summary>
        */
        private void Populate(
            Document document
            )
        {
            // Initialize a new page!
              Page page = new Page(document);
              document.Pages.Add(page);

              // Initialize the primitive composer (within the new page context)!
              PrimitiveComposer composer = new PrimitiveComposer(page);
              composer.SetFont(new StandardType1Font(document, StandardType1Font.FamilyEnum.Helvetica, true, false), 12);

              // Initialize the block composer (wrapping the primitive one)!
              BlockComposer blockComposer = new BlockComposer(composer);

              // Initialize the document layer configuration!
              LayerDefinition layerDefinition = document.Layer;
              document.PageMode = Document.PageModeEnum.Layers; // Shows the layers tab on document opening.

              // Get the root layers collection!
              Layers rootLayers = layerDefinition.Layers;

              // 1. Nested layers.
              {
            Layer nestedLayer = new Layer(document, "Nested layers");
            rootLayers.Add(nestedLayer);
            Layers nestedSubLayers = nestedLayer.Layers;

            Layer nestedLayer1 = new Layer(document, "Nested layer 1");
            nestedSubLayers.Add(nestedLayer1);

            Layer nestedLayer2 = new Layer(document, "Nested layer 2");
            nestedSubLayers.Add(nestedLayer2);
            nestedLayer2.Locked = true;

            /*
              NOTE: Text in this section is shown using PrimitiveComposer.
            */
            composer.BeginLayer(nestedLayer);
            composer.ShowText(nestedLayer.Title, new PointF(50, 50));
            composer.End();

            composer.BeginLayer(nestedLayer1);
            composer.ShowText(nestedLayer1.Title, new PointF(50, 75));
            composer.End();

            composer.BeginLayer(nestedLayer2);
            composer.ShowText(nestedLayer2.Title, new PointF(50, 100));
            composer.End();
              }

              // 2. Simple group (labeled group of non-nested, inclusive-state layers).
              {
            Layers simpleGroup = new Layers(document, "Simple group");
            rootLayers.Add(simpleGroup);

            Layer layer1 = new Layer(document, "Grouped layer 1");
            simpleGroup.Add(layer1);

            Layer layer2 = new Layer(document, "Grouped layer 2");
            simpleGroup.Add(layer2);

            /*
              NOTE: Text in this section is shown using BlockComposer along with PrimitiveComposer
              to demonstrate their flexible cooperation.
            */
            blockComposer.Begin(new RectangleF(50, 125, 200, 50), XAlignmentEnum.Left, YAlignmentEnum.Middle);

            composer.BeginLayer(layer1);
            blockComposer.ShowText(layer1.Title);
            composer.End();

            blockComposer.ShowBreak(new SizeF(0, 15));

            composer.BeginLayer(layer2);
            blockComposer.ShowText(layer2.Title);
            composer.End();

            blockComposer.End();
              }

              // 3. Radio group (labeled group of non-nested, exclusive-state layers).
              {
            Layers radioGroup = new Layers(document, "Radio group");
            rootLayers.Add(radioGroup);

            Layer radio1 = new Layer(document, "Radiogrouped layer 1");
            radioGroup.Add(radio1);
            radio1.Visible = true;

            Layer radio2 = new Layer(document, "Radiogrouped layer 2");
            radioGroup.Add(radio2);
            radio2.Visible = false;

            Layer radio3 = new Layer(document, "Radiogrouped layer 3");
            radioGroup.Add(radio3);
            radio3.Visible = false;

            // Register this option group in the layer configuration!
            LayerGroup options = new LayerGroup(document);
            options.Add(radio1);
            options.Add(radio2);
            options.Add(radio3);
            layerDefinition.OptionGroups.Add(options);

            /*
              NOTE: Text in this section is shown using BlockComposer along with PrimitiveComposer
              to demonstrate their flexible cooperation.
            */
            blockComposer.Begin(new RectangleF(50, 185, 200, 75), XAlignmentEnum.Left, YAlignmentEnum.Middle);

            composer.BeginLayer(radio1);
            blockComposer.ShowText(radio1.Title);
            composer.End();

            blockComposer.ShowBreak(new SizeF(0, 15));

            composer.BeginLayer(radio2);
            blockComposer.ShowText(radio2.Title);
            composer.End();

            blockComposer.ShowBreak(new SizeF(0, 15));

            composer.BeginLayer(radio3);
            blockComposer.ShowText(radio3.Title);
            composer.End();

            blockComposer.End();
              }

              // 4. Print-only layer.
              {
            Layer printOnlyLayer = new Layer(document, "Print-only layer");
            printOnlyLayer.Visible = false;
            printOnlyLayer.Printable = true;
            printOnlyLayer.Locked = true;
            rootLayers.Add(printOnlyLayer);

            composer.BeginLayer(printOnlyLayer);
            composer.ShowText(printOnlyLayer.Title, new PointF(50, 270));
            composer.End();
              }
              composer.Flush();
        }
Example #9
0
        public static void Main(string[] args)
        {
            if (args.Length != 3) {
                Console.WriteLine ("Usage: NbTest <background.pdf> <text> <output.pdf>");
                return;
            }

            if (!File.Exists (args [0])) {
                Console.Error.WriteLine ("Invalid text filename, it doesn't exist.");
                return;
            }

            string text = args [1];
            PDFFiles.File file = new PDFFiles.File (args [0]);
            Document document = file.Document;
            PageStamper stamper = new PageStamper (document.Pages [0]);
            PrimitiveComposer composer = stamper.Foreground;
            PDFFonts.Font font = PDFFonts.Font.Get (document, FONT_NAME);

            if (document.Layer == null) {
                document.Layer = new LayerDefinition (document);
            }

            document.PageMode = Document.PageModeEnum.Layers;

            Layer layer = new Layer(document, "Personalization");
            document.Layer.Layers.Add(layer);

            var margin = new RectangleF(MilimitersToPoints(2), MilimitersToPoints(1),
                                        MilimitersToPoints(6), MilimitersToPoints(1));
            //var frame = new RectangleF(MilimitersToPoints(0), MilimitersToPoints(179),
            //                           MilimitersToPoints(255), MilimitersToPoints(26));
            var frame = new RectangleF(MilimitersToPoints(105), MilimitersToPoints(155),
                                       MilimitersToPoints(100), MilimitersToPoints(26));
            var text_frame = new RectangleF(frame.X + margin.X,
                                            frame.Y + margin.Y,
                                            frame.Width - margin.Right,
                                            frame.Height - margin.Bottom);
            int font_size = GetFontSizeToFit(text, text_frame);

            composer.BeginLayer(layer);

            //composer.Rotate(90, new PointF(0, MilimitersToPoints(255)));

            composer.SetFillColor(new DeviceRGBColor(86f/255,175f/255,49f/255));
            composer.DrawRectangle(frame);
            composer.Fill();

            composer.SetFillColor(DeviceRGBColor.White);
            composer.SetFont(font, font_size);

            BlockComposer blockComposer = new BlockComposer(composer);
            blockComposer.Begin(text_frame, AlignmentXEnum.Center, AlignmentYEnum.Middle);
            blockComposer.ShowText(text);
            blockComposer.End();

            composer.End();
            stamper.Flush();

            file.Save(args [2], PDFFiles.SerializationModeEnum.Standard);

            file.Dispose();
        }
Example #10
0
        /**
          <summary>Populates a PDF file with contents.</summary>
        */
        private void Populate(
            Document document
            )
        {
            // Get the abstract barcode entity!
              EAN13Barcode barcode = new EAN13Barcode("8012345678901");
              // Create the reusable barcode within the document!
              XObject barcodeXObject = barcode.ToXObject(document);

              Pages pages = document.Pages;
              // Page 1.
              {
            Page page = new Page(document);
            pages.Add(page);
            SizeF pageSize = page.Size;

            PrimitiveComposer composer = new PrimitiveComposer(page);
            {
              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.Hyphenation = true;
              blockComposer.Begin(
            new RectangleF(
              Margin,
              Margin,
              pageSize.Width - Margin * 2,
              pageSize.Height - Margin * 2
              ),
            XAlignmentEnum.Left,
            YAlignmentEnum.Top
            );
              StandardType1Font bodyFont = new StandardType1Font(
            document,
            StandardType1Font.FamilyEnum.Courier,
            true,
            false
            );
              composer.SetFont(bodyFont,32);
              blockComposer.ShowText("Barcode sample"); blockComposer.ShowBreak();
              composer.SetFont(bodyFont,16);
              blockComposer.ShowText("Showing the EAN-13 Bar Code on different compositions:"); blockComposer.ShowBreak();
              blockComposer.ShowText("- page 1: on the lower right corner of the page, 100pt wide;"); blockComposer.ShowBreak();
              blockComposer.ShowText("- page 2: on the middle of the page, 1/3-page wide, 25 degree counterclockwise rotated;"); blockComposer.ShowBreak();
              blockComposer.ShowText("- page 3: filled page, 90 degree clockwise rotated."); blockComposer.ShowBreak();
              blockComposer.End();
            }

            // Show the barcode!
            composer.ShowXObject(
              barcodeXObject,
              new PointF(pageSize.Width - Margin, pageSize.Height - Margin),
              GeomUtils.Scale(barcodeXObject.Size, new SizeF(100,0)),
              XAlignmentEnum.Right,
              YAlignmentEnum.Bottom,
              0
              );
            composer.Flush();
              }

              // Page 2.
              {
            Page page = new Page(document);
            pages.Add(page);
            SizeF pageSize = page.Size;

            PrimitiveComposer composer = new PrimitiveComposer(page);
            // Show the barcode!
            composer.ShowXObject(
              barcodeXObject,
              new PointF(pageSize.Width / 2, pageSize.Height / 2),
              GeomUtils.Scale(barcodeXObject.Size, new SizeF(pageSize.Width / 3, 0)),
              XAlignmentEnum.Center,
              YAlignmentEnum.Middle,
              25
              );
            composer.Flush();
              }

              // Page 3.
              {
            Page page = new Page(document);
            pages.Add(page);
            SizeF pageSize = page.Size;

            PrimitiveComposer composer = new PrimitiveComposer(page);
            // Show the barcode!
            composer.ShowXObject(
              barcodeXObject,
              new PointF(pageSize.Width / 2, pageSize.Height / 2),
              new SizeF(pageSize.Height, pageSize.Width),
              XAlignmentEnum.Center,
              YAlignmentEnum.Middle,
              -90
              );
            composer.Flush();
              }
        }
Example #11
0
        private void Apply(
      PushButton field
      )
        {
            Document document = field.Document;
              Widget widget = field.Widgets[0];

              Appearance appearance = widget.Appearance;
              if(appearance == null)
              {widget.Appearance = appearance = new Appearance(document);}

              FormXObject normalAppearanceState;
              {
            SizeF size = widget.Box.Size;
            normalAppearanceState = new FormXObject(document, size);
            PrimitiveComposer composer = new PrimitiveComposer(normalAppearanceState);

            float lineWidth = 1;
            RectangleF frame = new RectangleF(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
            if(GraphicsVisibile)
            {
              composer.BeginLocalState();
              composer.SetLineWidth(lineWidth);
              composer.SetFillColor(BackColor);
              composer.SetStrokeColor(ForeColor);
              composer.DrawRectangle(frame, 5);
              composer.FillStroke();
              composer.End();
            }

            string title = (string)field.Value;
            if(title != null)
            {
              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.Begin(frame,XAlignmentEnum.Center,YAlignmentEnum.Middle);
              composer.SetFillColor(ForeColor);
              composer.SetFont(
            new StandardType1Font(
              document,
              StandardType1Font.FamilyEnum.Helvetica,
              true,
              false
              ),
            size.Height * 0.5
            );
              blockComposer.ShowText(title);
              blockComposer.End();
            }

            composer.Flush();
              }
              appearance.Normal[null] = normalAppearanceState;
        }
Example #12
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!
              Size breakSize = new Size(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(
            new RectangleF(
              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 #13
0
        private void PrintIdentificacaoEmitente(RectangleF area, BlockComposer bComp, PrimitiveComposer comp)
        {
            comp.SafeDrawRectangle(area);

            // Retângulo com padding
            RectangleF pRet = area.GetPaddedRectangleMm(1);

            var emitente = Danfe.Model.Emitente;

            var yAlign = Danfe.PossuiLogo ? YAlignmentEnum.Bottom : YAlignmentEnum.Middle;

            bComp.SafeBegin(pRet, XAlignmentEnum.Left, yAlign);

            double bestSize = DanfeCampo.AjustarFonte(emitente.Nome, Danfe.FontBold, pRet.Width, Danfe.PossuiLogo ? 10 : 12);
            comp.SetFont(Danfe.FontBold, bestSize);

            bComp.ShowText(emitente.Nome);
            bComp.ShowBreak();
            comp.SetFont(Danfe.Font, Danfe.PossuiLogo ? 7 : 8);
            bComp.ShowText(emitente.EnderecoLinha1);
            bComp.ShowBreak();
            bComp.ShowText(emitente.EnderecoBairro);
            bComp.ShowBreak();
            bComp.ShowText(emitente.EnderecoLinha3);

            if (!String.IsNullOrWhiteSpace(emitente.Telefone))
            {
                bComp.ShowBreak();
                bComp.ShowText(String.Format("Fone: {0}", Formatador.FormatarTelefone(emitente.Telefone)));
            }

            bComp.End();

            if (Danfe.PossuiLogo)
            {
                RectangleF logoRectangle = area;
                logoRectangle.Height = bComp.BoundBox.Top - logoRectangle.Y;
                PrintLogo(comp, logoRectangle);
            }
        }
Example #14
0
        private void PrintDescricaoDanfe(RectangleF area, BlockComposer bComp, PrimitiveComposer comp)
        {
            comp.SafeDrawRectangle(area);

            // Retangulo com padding
            RectangleF pRet = area.GetPaddedRectangleMm(1);

            // DANFE e descrição
            bComp.SafeBegin(pRet, XAlignmentEnum.Center, YAlignmentEnum.Top);
            comp.SetFont(Danfe.FontBold, 12);
            bComp.ShowText("DANFE");
            comp.SetFont(Danfe.Font, 6);
            bComp.ShowBreak(new SizeF(0, 1));
            bComp.ShowText(DescricaoDanfe);
            bComp.End();

            // Entrada, Saída
            RectangleF rEntrasaSaida = new RectangleF(pRet.X, bComp.BoundBox.Bottom + Utils.Mm2Pu(1.5F), pRet.Width, pRet.Bottom - bComp.BoundBox.Bottom);
            rEntrasaSaida = rEntrasaSaida.GetPaddedRectangleMm(0, 2.5F);

            comp.SetFont(Danfe.Font, 8);
            bComp.SafeBegin(rEntrasaSaida, XAlignmentEnum.Left, YAlignmentEnum.Top);
            bComp.ShowText("0 - Entrada\n1 - Saída");
            bComp.End();

            RectangleF rEntrasaSaida2 = bComp.BoundBox;
            rEntrasaSaida2 = new RectangleF(rEntrasaSaida.Right - bComp.BoundBox.Height, bComp.BoundBox.Y, bComp.BoundBox.Height, bComp.BoundBox.Height);
            comp.SafeDrawRectangle(rEntrasaSaida2);

            bComp.SafeBegin(rEntrasaSaida2, XAlignmentEnum.Center, YAlignmentEnum.Middle);
            bComp.ShowText(Danfe.Model.TipoNF.ToString());
            bComp.End();

            // Número Série e Folha
            RectangleF retEsquerdo = pRet;
            retEsquerdo.Width = Utils.Mm2Pu(8);

            RectangleF retDireito = pRet;
            retDireito.X = retEsquerdo.Right + Utils.Mm2Pu(1);
            retDireito.Width = pRet.Right - retDireito.Left;

            RetanguloFolha = retDireito;
            retDireito.Height -= (float)Danfe.FontBold.GetLineHeight(TamanhoFonteNumeracao);

            comp.SetFont(Danfe.FontBold, TamanhoFonteNumeracao);
            bComp.SafeBegin(retEsquerdo, XAlignmentEnum.Right, YAlignmentEnum.Bottom);
            bComp.ShowText("Nº\nSérie\nFolha");
            bComp.End();

            bComp.SafeBegin(retDireito, XAlignmentEnum.Left, YAlignmentEnum.Bottom);
            bComp.ShowText(String.Format("{0}\n{1}", Danfe.Model.NumeroNF.ToString(Formatador.FormatoNumeroNF), Danfe.Model.Serie));
            bComp.End();
        }
Example #15
0
        protected override void ToXObjectInternal(PrimitiveComposer comp)
        {
            BlockComposer bComp = new BlockComposer(comp);

            PrintIdentificacaoEmitente(RetEmitente, bComp, comp);
            PrintDescricaoDanfe(RetDescDanfe, bComp, comp);

            var emitente = Danfe.Model.Emitente;

            comp.SafeDrawRectangle(RetCodigoBarras);
            comp.SafeDrawRectangle(RetCampoVariavel);

            comp.SetFont(Danfe.Font, 8);
            bComp.SafeBegin(RetCampoVariavel, XAlignmentEnum.Center, YAlignmentEnum.Middle);
            bComp.ShowText(MensagemConsulta);
            bComp.End();

            comp.Stroke();

            var barcode = new Barcode128C(Danfe.Model.ChaveAcesso, RetCodigoBarras.Size).ToXObject(Danfe.Document);
            comp.ShowXObject(barcode, new PointF(RetCodigoBarras.X, RetCodigoBarras.Y));
        }
Example #16
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.

              SizeF pageSize = page.Size;

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

              // 3. Drawing the page contents...
              fonts::Font mainFont = new fonts::StandardType1Font(document, fonts::StandardType1Font.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(
              new RectangleF(
            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 = new fonts::StandardType1Font(document, fonts::StandardType1Font.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 PointF(x,y),
              XAlignmentEnum.Left,
              YAlignmentEnum.Middle,
              0
              );

            composer.SetFont(sampleFont, 10);
            RectangleF frame = new RectangleF(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 double[]{5,5}, 5));
              composer.DrawRectangle(frame);
              composer.Stroke();
            }
            composer.End();

            y+=step;
              }

              // 4. Flush the contents into the page!
              composer.Flush();
        }
Example #17
0
 private void PrintNumeroFolhas(int pagina, int nPaginas)
 {
     // Número de folhas
     var rFolhas = GetFolhaRect();
     BlockComposer bComp = new BlockComposer(_Composer);
     bComp.SafeBegin(rFolhas, XAlignmentEnum.Left, YAlignmentEnum.Bottom);
     _Composer.SetFont(_Danfe.FontBold, BlocoDadosNFe.TamanhoFonteNumeracao);
     bComp.ShowText(String.Format("{0}/{1}", pagina, nPaginas));
     bComp.End();
 }
Example #18
0
        protected override void ToXObjectInternal(PrimitiveComposer composer)
        {
            EmpresaViewModel empresa = null;

            if(Danfe.Model.TipoNF == 1)
            {
                empresa = Danfe.Model.Emitente;
            }
            else if(Danfe.Model.TipoNF == 0)
            {
                empresa = Danfe.Model.Destinatario;
            }
            else
            {
                throw new Exception("Tipo de NF não suportado.");
            }

            BlockComposer bComp = new BlockComposer(composer);

            composer.SafeDrawRectangle(RetNumeracao);
            composer.SafeDrawRectangle(RetRecebemos);

            composer.SetFont(Danfe.Font, 6);
            bComp.SafeBegin(RetRecebemos.GetPaddedRectangleMm(1), XAlignmentEnum.Left, YAlignmentEnum.Middle);
            bComp.ShowText(String.Format("RECEBEMOS DE {0} OS PRODUTOS E/OU SERVIÇOS CONSTANTES DA NOTA FISCAL ELETRÔNICA INDICADA ABAIXO.", empresa.Nome));
            bComp.End();

            // Numeração da NFe
            composer.SafeDrawRectangle(RetNumeracao);
            composer.SetFont(Danfe.FontBold, 12);
            bComp.SafeBegin(RetNumeracao, XAlignmentEnum.Center, YAlignmentEnum.Middle);
            bComp.ShowText(String.Format("NF-e\nNº {0}\nSérie {1}", Danfe.Model.NumeroNF.ToString(Formatador.FormatoNumeroNF), Danfe.Model.Serie));
            bComp.End();

            composer.Stroke();

            // Linha pontilhada
            composer.BeginLocalState();
            composer.SetLineDash(new org.pdfclown.documents.contents.LineDash(new double[] { 3, 2 }));
            composer.DrawLine(new PointF(InternalRectangle.Left, Size.Height - MargemLinhaPontilhada), new PointF(InternalRectangle.Right, Size.Height - MargemLinhaPontilhada));
            composer.Stroke();
            composer.End();
        }
Example #19
0
        /**
          <summary>Populates a PDF file with contents.</summary>
        */
        private void Populate(
            Document document,
            XObject form
            )
        {
            // 1. 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.

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

              // 3. Inserting contents...
              SizeF pageSize = page.Size;
              // 3.1. Showing the form on the page...
              {
            SizeF formSize = form.Size;
            // Form 1.
            composer.ShowXObject(
              form,
              new PointF(pageSize.Width/2,pageSize.Height/2),
              GeomUtils.Scale(formSize, new SizeF(300,0)),
              XAlignmentEnum.Center,
              YAlignmentEnum.Middle,
              45
              );
            // Form 2.
            composer.ShowXObject(
              form,
              new PointF(0,pageSize.Height),
              GeomUtils.Scale(formSize, new SizeF(0,300)),
              XAlignmentEnum.Left,
              YAlignmentEnum.Bottom,
              0
              );
            // Form 3.
            composer.ShowXObject(
              form,
              new PointF(pageSize.Width,pageSize.Height),
              new SizeF(80,200),
              XAlignmentEnum.Right,
              YAlignmentEnum.Bottom,
              0
              );
              }
              // 3.2. Showing the comments on the page...
              {
            BlockComposer blockComposer = new BlockComposer(composer);
            RectangleF frame = new RectangleF(
              18,
              18,
              pageSize.Width * .5f,
              pageSize.Height * .5f
              );
            blockComposer.Begin(frame,XAlignmentEnum.Justify,YAlignmentEnum.Top);
            StandardType1Font bodyFont = new StandardType1Font(
              document,
              StandardType1Font.FamilyEnum.Courier,
              true,
              false
              );
            composer.SetFont(bodyFont,24);
            blockComposer.ShowText("Page-to-form sample");
            SizeF breakSize = new SizeF(0,8);
            blockComposer.ShowBreak(breakSize);
            composer.SetFont(bodyFont,8);
            blockComposer.ShowText("This sample shows how to convert a page to a reusable form that can be placed multiple times on other pages scaling, rotating, anchoring and aligning it.");
            blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("On this page you can see some of the above-mentioned transformations:");
            breakSize.Width = 8;
            blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("1. anchored to the center of the page, rotated by 45 degrees counterclockwise, 300 point wide (preserved proportions);"); blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("2. anchored to the bottom-left corner of the page, 300 point high (preserved proportions);"); blockComposer.ShowBreak(breakSize);
            blockComposer.ShowText("3. anchored to the bottom-right of the page, 80 point wide and 200 point high (altered proportions).");
            blockComposer.End();
              }

              // 4. Flush the contents into the content stream!
              composer.Flush();
        }
Example #20
0
        /// <summary>
        /// Imprime o campo no composer.
        /// </summary>
        /// <param name="comp"></param>
        public void Print(PrimitiveComposer comp, org.pdfclown.documents.contents.fonts.Font fonte, org.pdfclown.documents.contents.fonts.Font fonteBold)
        {
            BlockComposer bComp = new BlockComposer(comp);
            RectangleF pRect = Retangulo.GetPaddedRectangle(PaddingHorizontal, PaddingHorizontal, PaddingSuperior, PaddingInferior);

            comp.SetFont(fonteBold, TamanhoFonteCabecalho);
            ValidadeRectangle(pRect, comp);
            bComp.SafeBegin(pRect, XAlignmentEnum.Left, YAlignmentEnum.Top);
            bComp.ShowText(Cabecalho.ToUpper());
            bComp.End();

            bComp.LineSpace = new Length(LineSpace, Length.UnitModeEnum.Absolute);

            if (!String.IsNullOrWhiteSpace(Corpo))
            {
                org.pdfclown.documents.contents.fonts.Font fonteCorpo = IsCorpoNegrito ? fonteBold : fonte;

                double largura = fonteCorpo.GetWidth(Corpo, CorpoTamanhoFonte);
                double novoTamanho = CorpoTamanhoFonte;

                if (!MultiLinha && largura > pRect.Width)
                {
                    novoTamanho = (CorpoTamanhoFonte * pRect.Width) / largura - Utils.Mm2Pu(0.005F);
                    comp.SetFont(fonteCorpo, novoTamanho);
                }

                comp.SetFont(fonteCorpo, novoTamanho);

                if (CorpoAlinhamentoY == YAlignmentEnum.Top)
                {
                    float yOffSet = (float)fonteBold.GetLineHeight(TamanhoFonteCabecalho) + LineSpace;
                    pRect.Y += yOffSet;
                    pRect.Height -= yOffSet;
                }

                ValidadeRectangle(pRect, comp);
                bComp.SafeBegin(pRect, CorpoAlinhamentoX, CorpoAlinhamentoY);
                bComp.ShowText(Corpo);
                bComp.End();
            }

            comp.SafeDrawRectangle(Retangulo);
        }
Example #21
0
        private void Apply(
      CheckBox field
      )
        {
            Document document = field.Document;
              foreach(Widget widget in field.Widgets)
              {
            {
              PdfDictionary widgetDataObject = widget.BaseDataObject;
              widgetDataObject[PdfName.DA] = new PdfString("/ZaDb 0 Tf 0 0 0 rg");
              widgetDataObject[PdfName.MK] = new PdfDictionary(
            new PdfName[]
            {
              PdfName.BG,
              PdfName.BC,
              PdfName.CA
            },
            new PdfDirectObject[]
            {
              new PdfArray(new PdfDirectObject[]{PdfReal.Get(0.9412), PdfReal.Get(0.9412), PdfReal.Get(0.9412)}),
              new PdfArray(new PdfDirectObject[]{PdfInteger.Default, PdfInteger.Default, PdfInteger.Default}),
              new PdfString("4")
            }
            );
              widgetDataObject[PdfName.BS] = new PdfDictionary(
            new PdfName[]
            {
              PdfName.W,
              PdfName.S
            },
            new PdfDirectObject[]
            {
              PdfReal.Get(0.8),
              PdfName.S
            }
            );
              widgetDataObject[PdfName.H] = PdfName.P;
            }

            Appearance appearance = widget.Appearance;
            if(appearance == null)
            {widget.Appearance = appearance = new Appearance(document);}

            SizeF size = widget.Box.Size;

            AppearanceStates normalAppearance = appearance.Normal;
            FormXObject onState = new FormXObject(document, size);
            normalAppearance[PdfName.Yes] = onState;

              //TODO:verify!!!
              //   appearance.getRollover().put(PdfName.Yes,onState);
              //   appearance.getDown().put(PdfName.Yes,onState);
              //   appearance.getRollover().put(PdfName.Off,offState);
              //   appearance.getDown().put(PdfName.Off,offState);

            float lineWidth = 1;
            RectangleF frame = new RectangleF(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
            {
              PrimitiveComposer composer = new PrimitiveComposer(onState);

              if(GraphicsVisibile)
              {
            composer.BeginLocalState();
            composer.SetLineWidth(lineWidth);
            composer.SetFillColor(BackColor);
            composer.SetStrokeColor(ForeColor);
            composer.DrawRectangle(frame, 5);
            composer.FillStroke();
            composer.End();
              }

              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.Begin(frame,XAlignmentEnum.Center,YAlignmentEnum.Middle);
              composer.SetFillColor(ForeColor);
              composer.SetFont(
            new StandardType1Font(
              document,
              StandardType1Font.FamilyEnum.ZapfDingbats,
              true,
              false
              ),
            size.Height * 0.8
            );
              blockComposer.ShowText(new String(new char[]{CheckSymbol}));
              blockComposer.End();

              composer.Flush();
            }

            FormXObject offState = new FormXObject(document, size);
            normalAppearance[PdfName.Off] = offState;
            {
              if(GraphicsVisibile)
              {
            PrimitiveComposer composer = new PrimitiveComposer(offState);

            composer.BeginLocalState();
            composer.SetLineWidth(lineWidth);
            composer.SetFillColor(BackColor);
            composer.SetStrokeColor(ForeColor);
            composer.DrawRectangle(frame, 5);
            composer.FillStroke();
            composer.End();

            composer.Flush();
              }
            }
              }
        }
        private void PrintTextCell(PrimitiveComposer composer, String text, RectangleF rect, XAlignmentEnum align = XAlignmentEnum.Center)
        {
            if (!String.IsNullOrWhiteSpace(text))
            {
                text = text.Replace(Char.ConvertFromUtf32(160), Char.ConvertFromUtf32(32));
            }

            BlockComposer bComp = new BlockComposer(composer);
            bComp.SafeBegin(rect, align, YAlignmentEnum.Top);
            bComp.ShowText(text);
            bComp.End();
            CurrentY = Math.Max(CurrentY, bComp.BoundBox.Bottom);
        }
Example #23
0
        private void BuildLinks(
            Document document
            )
        {
            Pages pages = document.Pages;
              Page page = new Page(document);
              pages.Add(page);

              StandardType1Font font = new StandardType1Font(
            document,
            StandardType1Font.FamilyEnum.Courier,
            true,
            false
            );

              PrimitiveComposer composer = new PrimitiveComposer(page);
              BlockComposer blockComposer = new BlockComposer(composer);

              /*
            2.1. Goto-URI link.
              */
              {
            blockComposer.Begin(new RectangleF(30,100,200,50),XAlignmentEnum.Left,YAlignmentEnum.Middle);
            composer.SetFont(font,12);
            blockComposer.ShowText("Go-to-URI link");
            composer.SetFont(font,8);
            blockComposer.ShowText("\nIt allows you to navigate to a network resource.");
            composer.SetFont(font,5);
            blockComposer.ShowText("\n\nClick on the box to go to the project's SourceForge.net repository.");
            blockComposer.End();

            try
            {
              /*
            NOTE: This statement instructs the PDF viewer to navigate to the given URI when the link is clicked.
              */
              annotations::Link link = new annotations::Link(
            page,
            new Rectangle(240,100,100,50),
            "Link annotation",
            new GoToURI(
              document,
              new Uri("http://www.sourceforge.net/projects/clown")
              )
            );
              link.Border = new annotations::Border(
            document,
            3,
            annotations::Border.StyleEnum.Beveled,
            null
            );
            }
            catch(Exception exception)
            {throw new Exception("",exception);}
              }

              /*
            2.2. Embedded-goto link.
              */
              {
            string filePath = PromptFileChoice("Please select a PDF file to attach");

            /*
              NOTE: These statements instruct PDF Clown to attach a PDF file to the current document.
              This is necessary in order to test the embedded-goto functionality,
              as you can see in the following link creation (see below).
            */
            int fileAttachmentPageIndex = page.Index;
            string fileAttachmentName = "attachedSamplePDF";
            string fileName = System.IO.Path.GetFileName(filePath);
            annotations::FileAttachment attachment = new annotations::FileAttachment(
              page,
              new Rectangle(0, -20, 10, 10),
              "File attachment annotation",
              FileSpecification.Get(
            EmbeddedFile.Get(
              document,
              filePath
              ),
            fileName
            )
              );
            attachment.Name = fileAttachmentName;
            attachment.IconType = annotations::FileAttachment.IconTypeEnum.PaperClip;

            blockComposer.Begin(new RectangleF(30,170,200,50),XAlignmentEnum.Left,YAlignmentEnum.Middle);
            composer.SetFont(font,12);
            blockComposer.ShowText("Go-to-embedded link");
            composer.SetFont(font,8);
            blockComposer.ShowText("\nIt allows you to navigate to a destination within an embedded PDF file.");
            composer.SetFont(font,5);
            blockComposer.ShowText("\n\nClick on the button to go to the 2nd page of the attached PDF file (" + fileName + ").");
            blockComposer.End();

            /*
              NOTE: This statement instructs the PDF viewer to navigate to the page 2 of a PDF file
              attached inside the current document as described by the FileAttachment annotation on page 1 of the current document.
            */
            annotations::Link link = new annotations::Link(
              page,
              new Rectangle(240,170,100,50),
              "Link annotation",
              new GoToEmbedded(
            document,
            new GoToEmbedded.PathElement(
              document,
              fileAttachmentPageIndex, // Page of the current document containing the file attachment annotation of the target document.
              fileAttachmentName, // Name of the file attachment annotation corresponding to the target document.
              null // No sub-target.
              ), // Target represents the document to go to.
            new RemoteDestination(
              document,
              1, // Show the page 2 of the target document.
              Destination.ModeEnum.Fit, // Show the target document page entirely on the screen.
              null,
              null
              ) // The destination must be within the target document.
            )
              );
            link.Border = new annotations::Border(
              document,
              1,
              annotations::Border.StyleEnum.Dashed,
              new LineDash(new double[]{8,5,2,5})
              );
              }

              /*
            2.3. Textual link.
              */
              {
            blockComposer.Begin(new RectangleF(30,240,200,50),XAlignmentEnum.Left,YAlignmentEnum.Middle);
            composer.SetFont(font,12);
            blockComposer.ShowText("Textual link");
            composer.SetFont(font,8);
            blockComposer.ShowText("\nIt allows you to expose any kind of link (including the above-mentioned types) as text.");
            composer.SetFont(font,5);
            blockComposer.ShowText("\n\nClick on the text links to go either to the project's SourceForge.net repository or to the project's home page.");
            blockComposer.End();

            try
            {
              composer.BeginLocalState();
              composer.SetFont(font,10);
              composer.SetFillColor(DeviceRGBColor.Get(System.Drawing.Color.Blue));
              composer.ShowText(
            "PDF Clown Project's repository at SourceForge.net",
            new PointF(240,265),
            XAlignmentEnum.Left,
            YAlignmentEnum.Middle,
            0,
            new GoToURI(
              document,
              new Uri("http://www.sourceforge.net/projects/clown")
              )
            );
              composer.ShowText(
            "PDF Clown Project's home page",
            new PointF(240,285),
            XAlignmentEnum.Left,
            YAlignmentEnum.Bottom,
            -90,
            new GoToURI(
              document,
              new Uri("http://www.pdfclown.org")
              )
            );
              composer.End();
            }
            catch
            {}
              }

              composer.Flush();
        }
Example #24
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.

              SizeF 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!
              RectangleF frame = new RectangleF(
            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 = new RectangleF(
            (float)blockComposer.BoundBox.X,
            (float)blockComposer.BoundBox.Y + blockComposer.BoundBox.Height,
            (float)blockComposer.BoundBox.Width,
            (float)pageSize.Height - Margin_Y - (blockComposer.BoundBox.Y + 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!
              SizeF breakSize = new SizeF(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 PointF(
              pageSize.Width - 50,
              pageSize.Height - 25
              )
            );
              blockComposer = new BlockComposer(composer);
              blockComposer.Begin(
            new RectangleF(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 #25
0
        static int GetFontSizeToFit(string text, RectangleF frame)
        {
            PDFFiles.File file = new PDFFiles.File();
            Page page = new Page(file.Document);
            PDFFonts.Font font = PDFFonts.Font.Get(file.Document, FONT_NAME);
            PrimitiveComposer composer;
            BlockComposer blockComposer;
            int font_size = (int)frame.Height;
            int chars = 0;

            file.Document.Pages.Add(page);
            composer = new PrimitiveComposer(page);
            blockComposer = new BlockComposer(composer);

            while (blockComposer.BoundBox.Height > frame.Height || text.Length != chars) {
                blockComposer.Begin(frame, AlignmentXEnum.Center, AlignmentYEnum.Middle);
                composer.SetFont(font, font_size);
                chars = blockComposer.ShowText(text);
                blockComposer.End();
                Console.WriteLine ("FontSize: {0}, Text Size: [w:{1} h:{2}], Frame Size: [w:{3} h:{4}], Chars: {5}", font_size,
                                   blockComposer.BoundBox.Width, blockComposer.BoundBox.Height,
                                   frame.Width, frame.Height, chars);
                font_size--;
            }

            file.Dispose();

            return font_size + 1;
        }
Example #26
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.

              SizeF pageSize = page.Size;

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

              // 3. Drawing the page contents...
              fonts::Font mainFont = new fonts::StandardType1Font(document, fonts::StandardType1Font.FamilyEnum.Courier, true, false);
              int stepCount = 5;
              int step = (int)(pageSize.Height) / (stepCount + 1);
              BlockComposer blockComposer = new BlockComposer(composer);
              {
            blockComposer.Begin(
              new RectangleF(
            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 = new fonts::StandardType1Font(document, fonts::StandardType1Font.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++)
            {
              RectangleF frame = new RectangleF(
                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 SizeF(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 double[]{1,4}, 4));
                composer.DrawRectangle(blockComposer.Frame);
                composer.Stroke();
              }
              composer.End();

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

              // 4. Flush the contents into the page!
              composer.Flush();
        }
Example #27
0
        /// <summary>
        /// Imprime o cabeçalho do bloco.
        /// </summary>
        private void PrintCabecalho(PrimitiveComposer comp)
        {
            BlockComposer bComp = new BlockComposer(comp);

            RectangleF rect = new RectangleF(0, 0, Size.Width, Danfe.CabecalhoBlocoAltura);
            rect = rect.GetPaddedRectangleMm(0, 0, 1, 0.3F);

            comp.SetFont(Danfe.FontBold, 5);
            bComp.SafeBegin(rect, XAlignmentEnum.Left, YAlignmentEnum.Bottom);
            bComp.ShowText(Cabecalho.ToUpper());
            bComp.End();

            comp.Flush();
        }
Example #28
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.

              SizeF pageSize = page.Size;

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

              // 3. Drawing the page contents...
              fonts::Font mainFont = new fonts::StandardType1Font(document, fonts::StandardType1Font.FamilyEnum.Courier, true, false);
              int stepCount = 5;
              int step = (int)pageSize.Height / (stepCount + 1);
              BlockComposer blockComposer = new BlockComposer(composer);
              {
            blockComposer.Begin(
              new RectangleF(
            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 = new fonts::StandardType1Font(document, fonts::StandardType1Font.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;
            {
              RectangleF frame = new RectangleF(
            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 double[]{5,5}, 5));
            composer.DrawRectangle(frame);
            composer.Stroke();
              }
              composer.End();
            }
            {
              RectangleF frame = new RectangleF(
            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 double[]{5,5}, 5));
            composer.DrawRectangle(frame);
            composer.Stroke();
              }
              composer.End();
            }
              }

              // 4. Flush the contents into the page!
              composer.Flush();
        }
Example #29
0
        private void Populate(
            Document document
            )
        {
            /*
            NOTE: In order to insert a field into a document, you have to follow these steps:
            1. Define the form fields collection that will gather your fields (NOTE: the form field collection is global to the document);
            2. Define the pages where to place the fields;
            3. Define the appearance style to render your fields;
            4. Create each field of yours:
              4.1. instantiate your field into the page;
              4.2. apply the appearance style to your field;
              4.3. insert your field into the fields collection.
              */

              // 1. Define the form fields collection!
              Form form = document.Form;
              Fields fields = form.Fields;

              // 2. Define the page where to place the fields!
              Page page = new Page(document);
              document.Pages.Add(page);

              // 3. Define the appearance style to apply to the fields!
              DefaultStyle fieldStyle = new DefaultStyle();
              fieldStyle.FontSize = 12;
              fieldStyle.GraphicsVisibile = true;

              PrimitiveComposer composer = new PrimitiveComposer(page);
              composer.SetFont(
            new StandardType1Font(
              document,
              StandardType1Font.FamilyEnum.Courier,
              true,
              false
              ),
            14
            );

              // 4. Field creation.
              // 4.a. Push button.
              {
            composer.ShowText(
              "PushButton:",
              new PointF(140, 68),
              XAlignmentEnum.Right,
              YAlignmentEnum.Middle,
              0
              );

            Widget fieldWidget = new Widget(
              page,
              new RectangleF(150, 50, 136, 36)
              );
            WidgetActions fieldWidgetActions = new WidgetActions(fieldWidget);
            fieldWidget.Actions = fieldWidgetActions;
            fieldWidgetActions.OnActivate = new JavaScript(
              document,
              "app.alert(\"Radio button currently selected: '\" + this.getField(\"myRadio\").value + \"'.\",3,0,\"Activation event\");"
              );
            PushButton field = new PushButton(
              "okButton",
              fieldWidget,
              "Push" // Current value.
              ); // 4.1. Field instantiation.
            fields.Add(field); // 4.2. Field insertion into the fields collection.
            fieldStyle.Apply(field); // 4.3. Appearance style applied.

            {
              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.Begin(new RectangleF(296,50,page.Size.Width-336,36),XAlignmentEnum.Left,YAlignmentEnum.Middle);
              composer.SetFont(composer.State.Font,7);
              blockComposer.ShowText("If you click this push button, a javascript action should prompt you an alert box responding to the activation event triggered by your PDF viewer.");
              blockComposer.End();
            }
              }

              // 4.b. Check box.
              {
            composer.ShowText(
              "CheckBox:",
              new PointF(140, 118),
              XAlignmentEnum.Right,
              YAlignmentEnum.Middle,
              0
              );
            CheckBox field = new CheckBox(
              "myCheck",
              new Widget(
            page,
            new RectangleF(150, 100, 36, 36)
            ),
              true // Current value.
              ); // 4.1. Field instantiation.
            fieldStyle.Apply(field);
            fields.Add(field);
            field = new CheckBox(
              "myCheck2",
              new Widget(
            page,
            new RectangleF(200, 100, 36, 36)
            ),
              true // Current value.
              ); // 4.1. Field instantiation.
            fieldStyle.Apply(field);
            fields.Add(field);
            field = new CheckBox(
              "myCheck3",
              new Widget(
            page,
            new RectangleF(250, 100, 36, 36)
            ),
              false // Current value.
              ); // 4.1. Field instantiation.
            fields.Add(field); // 4.2. Field insertion into the fields collection.
            fieldStyle.Apply(field); // 4.3. Appearance style applied.
              }

              // 4.c. Radio button.
              {
            composer.ShowText(
              "RadioButton:",
              new PointF(140, 168),
              XAlignmentEnum.Right,
              YAlignmentEnum.Middle,
              0
              );
            RadioButton field = new RadioButton(
              "myRadio",
              /*
            NOTE: A radio button field typically combines multiple alternative widgets.
              */
              new DualWidget[]
              {
            new DualWidget(
              page,
              new RectangleF(150, 150, 36, 36),
              "first"
              ),
            new DualWidget(
              page,
              new RectangleF(200, 150, 36, 36),
              "second"
              ),
            new DualWidget(
              page,
              new RectangleF(250, 150, 36, 36),
              "third"
              )
              },
              "second" // Selected item (it MUST correspond to one of the available widgets' names).
              ); // 4.1. Field instantiation.
            fields.Add(field); // 4.2. Field insertion into the fields collection.
            fieldStyle.Apply(field); // 4.3. Appearance style applied.
              }

              // 4.d. Text field.
              {
            composer.ShowText(
              "TextField:",
              new PointF(140, 218),
              XAlignmentEnum.Right,
              YAlignmentEnum.Middle,
              0
              );
            TextField field = new TextField(
              "myText",
              new Widget(
            page,
            new RectangleF(150, 200, 200, 36)
            ),
              "Carmen Consoli" // Current value.
              ); // 4.1. Field instantiation.
            field.SpellChecked = false; // Avoids text spell check.
            FieldActions fieldActions = new FieldActions(document);
            field.Actions = fieldActions;
            fieldActions.OnValidate = new JavaScript(
              document,
              "app.alert(\"Text '\" + this.getField(\"myText\").value + \"' has changed!\",3,0,\"Validation event\");"
              );
            fields.Add(field); // 4.2. Field insertion into the fields collection.
            fieldStyle.Apply(field); // 4.3. Appearance style applied.

            {
              BlockComposer blockComposer = new BlockComposer(composer);
              blockComposer.Begin(new RectangleF(360,200,page.Size.Width-400,36),XAlignmentEnum.Left,YAlignmentEnum.Middle);
              composer.SetFont(composer.State.Font,7);
              blockComposer.ShowText("If you leave this text field after changing its content, a javascript action should prompt you an alert box responding to the validation event triggered by your PDF viewer.");
              blockComposer.End();
            }
              }

              // 4.e. Choice fields.
              {
            // Preparing the item list that we'll use for choice fields (a list box and a combo box (see below))...
            ChoiceItems items = new ChoiceItems(document);
            items.Add("Tori Amos");
            items.Add("Anouk");
            items.Add("Joan Baez");
            items.Add("Rachele Bastreghi");
            items.Add("Anna Calvi");
            items.Add("Tracy Chapman");
            items.Add("Carmen Consoli");
            items.Add("Ani DiFranco");
            items.Add("Cristina Dona'");
            items.Add("Nathalie Giannitrapani");
            items.Add("PJ Harvey");
            items.Add("Billie Holiday");
            items.Add("Joan As Police Woman");
            items.Add("Joan Jett");
            items.Add("Janis Joplin");
            items.Add("Angelique Kidjo");
            items.Add("Patrizia Laquidara");
            items.Add("Annie Lennox");
            items.Add("Loreena McKennitt");
            items.Add("Joni Mitchell");
            items.Add("Alanis Morissette");
            items.Add("Yael Naim");
            items.Add("Noa");
            items.Add("Sinead O'Connor");
            items.Add("Dolores O'Riordan");
            items.Add("Nina Persson");
            items.Add("Brisa Roche'");
            items.Add("Roberta Sammarelli");
            items.Add("Cristina Scabbia");
            items.Add("Nina Simone");
            items.Add("Skin");
            items.Add("Patti Smith");
            items.Add("Fatima Spar");
            items.Add("Thony (F.V.Caiozzo)");
            items.Add("Paola Turci");
            items.Add("Sarah Vaughan");
            items.Add("Nina Zilli");

            // 4.e1. List box.
            {
              composer.ShowText(
            "ListBox:",
            new PointF(140, 268),
            XAlignmentEnum.Right,
            YAlignmentEnum.Middle,
            0
            );
              ListBox field = new ListBox(
            "myList",
            new Widget(
              page,
              new RectangleF(150, 250, 200, 70)
              )
            ); // 4.1. Field instantiation.
              field.Items = items; // List items assignment.
              field.MultiSelect = false; // Multiple items may not be selected simultaneously.
              field.Value = "Carmen Consoli"; // Selected item.
              fields.Add(field); // 4.2. Field insertion into the fields collection.
              fieldStyle.Apply(field); // 4.3. Appearance style applied.
            }

            // 4.e2. Combo box.
            {
              composer.ShowText(
            "ComboBox:",
            new PointF(140, 350),
            XAlignmentEnum.Right,
            YAlignmentEnum.Middle,
            0
            );
              ComboBox field = new ComboBox(
            "myCombo",
            new Widget(
              page,
              new RectangleF(150, 334, 200, 36)
              )
            ); // 4.1. Field instantiation.
              field.Items = items; // Combo items assignment.
              field.Editable = true; // Text may be edited.
              field.SpellChecked = false; // Avoids text spell check.
              field.Value = "Carmen Consoli"; // Selected item.
              fields.Add(field); // 4.2. Field insertion into the fields collection.
              fieldStyle.Apply(field); // 4.3. Appearance style applied.
            }
              }

              composer.Flush();
        }
Example #30
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.

              SizeF pageSize = page.Size;

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

              // 3. Drawing the page contents...
              fonts::Font mainFont = new fonts::StandardType1Font(document, fonts::StandardType1Font.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(
              new RectangleF(
            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 = new fonts::StandardType1Font(document, fonts::StandardType1Font.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 PointF(x,y),
            XAlignmentEnum.Left,
            YAlignmentEnum.Middle,
            0
            );

              composer.SetFont(sampleFont, 10);
              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();
            }

            RectangleF frame = new RectangleF(
              frameX,
              y-step*.4f,
              200,
              step*.8f
              );
            blockComposer.Begin(frame,xAlignment,yAlignment);
            blockComposer.ShowText(
              "Demonstrating how to constrain text inside a page area using PDF Clown. See the other available code samples (such as TypesettingSample) to discover more functionality details."
              );
            blockComposer.End();

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

              y+=step;
            }
              }

              // 4. Flush the contents into the page!
              composer.Flush();
        }