protected void AddTextDataToPdfPage(PDFDoc pdfDoc, pdftron.PDF.Page pdfPage, string text)
        {
            var elementWriter = new ElementWriter();

            try
            {
                elementWriter.Begin(pdfPage);

                var elementBuilder = new ElementBuilder();
                var textFont       = Font.Create(pdfDoc, Font.StandardType1Font.e_times_roman);
                var textFontSize   = 10.0;
                var textElement    = elementBuilder.CreateTextBegin(textFont, textFontSize);
                elementWriter.WriteElement(textElement);
                elementBuilder.CreateTextRun(text);
                elementWriter.WriteElement(textElement);
                var textEnd = elementBuilder.CreateTextEnd();
                elementWriter.WriteElement(textEnd);

                elementWriter.Flush();
                elementWriter.End();
            }
            finally
            {
                elementWriter.Dispose();
            }
        }
Beispiel #2
0
        static void AddCovePage(PDFDoc doc)
        {
            // Here we dynamically generate cover page (please see ElementBuilder
            // sample for more extensive coverage of PDF creation API).
            Page page = doc.PageCreate(new Rect(0, 0, 200, 200));

            using (ElementBuilder b = new ElementBuilder())
                using (ElementWriter w = new ElementWriter())
                {
                    w.Begin(page);
                    Font font = Font.Create(doc, "Arial", "");
                    w.WriteElement(b.CreateTextBegin(font, 12));
                    Element e = b.CreateTextRun("My PDF Collection");
                    e.SetTextMatrix(1, 0, 0, 1, 50, 96);
                    e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                    e.GetGState().SetFillColor(new ColorPt(1, 0, 0));
                    w.WriteElement(e);
                    w.WriteElement(b.CreateTextEnd());
                    w.End();
                    doc.PagePushBack(page);
                }

            // Alternatively we could import a PDF page from a template PDF document
            // (for an example please see PDFPage sample project).
            // ...
        }
        // Creates some text and associate it with the text layer
        static Obj CreateGroup3(PDFDoc doc, Obj layer)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder builder = new ElementBuilder())
                {
                    writer.Begin(doc);

                    // Begin writing a block of text
                    Element element = builder.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 120);
                    writer.WriteElement(element);

                    element = builder.CreateTextRun("A text layer!");

                    // Rotate text 45 degrees, than translate 180 pts horizontally and 100 pts vertically.
                    Matrix2D transform = Matrix2D.RotationMatrix(-45 * (3.1415 / 180.0));
                    transform.Concat(1, 0, 0, 1, 180, 100);
                    element.SetTextMatrix(transform);

                    writer.WriteElement(element);
                    writer.WriteElement(builder.CreateTextEnd());

                    Obj grp_obj = writer.End();

                    // Indicate that this form (content group) belongs to the given layer (OCG).
                    grp_obj.PutName("Subtype", "Form");
                    grp_obj.Put("OC", layer);
                    grp_obj.PutRect("BBox", 0, 0, 1000, 1000);                  // Set the clip box for the content.

                    return(grp_obj);
                }
        }
Beispiel #4
0
 public void Add <T>(IEnumerable <T> values, ElementWriter <T> writer, bool storesCompoundValues)
 => AddArray(() =>
 {
     foreach (var value in values)
     {
         writer(value);
     }
 }, storesCompoundValues);
Beispiel #5
0
        static void Main(string[] args)
        {
            IElementReader reader = new ElementReader();
            var            items  = reader.Read(filePathFromXML);

            IElementWriter writer = new ElementWriter();

            writer.Write(items, filePathToJSON);
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            IElementReader reader = new ElementReader();
            var            items  = reader.Read(path1);

            IElementWriter writer = new ElementWriter();

            writer.Write(items, path2);
        }
        // Creates some content (3 images) and associate them with the image layer
        static Obj CreateGroup1(PDFDoc doc, Obj layer)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder builder = new ElementBuilder())
                {
                    writer.Begin(doc);

                    // Create an Image that can be reused in the document or on the same page.
                    Image img = Image.Create(doc.GetSDFDoc(), (input_path + "peppers.jpg"));

                    Element element = builder.CreateImage(img, new Matrix2D(img.GetImageWidth() / 2, -145, 20, img.GetImageHeight() / 2, 200, 150));
                    writer.WritePlacedElement(element);

                    GState gstate = element.GetGState();                // use the same image (just change its matrix)
                    gstate.SetTransform(200, 0, 0, 300, 50, 450);
                    writer.WritePlacedElement(element);

                    // use the same image again (just change its matrix).
                    writer.WritePlacedElement(builder.CreateImage(img, 300, 600, 200, -150));

                    Obj grp_obj = writer.End();

                    // Indicate that this form (content group) belongs to the given layer (OCG).
                    grp_obj.PutName("Subtype", "Form");
                    grp_obj.Put("OC", layer);
                    grp_obj.PutRect("BBox", 0, 0, 1000, 1000);              // Set the clip box for the content.

                    // As an example of further configuration, set the image layer to
                    // be visible on screen, but not visible when printed...

                    // The AS entry is an auto state array consisting of one or more usage application
                    // dictionaries that specify how conforming readers shall automatically set the
                    // state of optional content groups based on external factors.
                    Obj cfg        = doc.GetOCGConfig().GetSDFObj();
                    Obj auto_state = cfg.FindObj("AS");
                    if (auto_state == null)
                    {
                        auto_state = cfg.PutArray("AS");
                    }
                    Obj print_state = auto_state.PushBackDict();
                    print_state.PutArray("Category").PushBackName("Print");
                    print_state.PutName("Event", "Print");
                    print_state.PutArray("OCGs").PushBack(layer);

                    Obj layer_usage = layer.PutDict("Usage");

                    Obj view_setting = layer_usage.PutDict("View");
                    view_setting.PutName("ViewState", "ON");

                    Obj print_setting = layer_usage.PutDict("Print");
                    print_setting.PutName("PrintState", "OFF");

                    return(grp_obj);
                }
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path      = "../../TestFiles/";
            string output_path     = "../../TestFiles/Output/";
            string input_filename  = "newsletter.pdf";
            string output_filename = "newsletter_edited.pdf";

            try
            {
                Console.WriteLine("Opening the input file...");
                using (PDFDoc doc = new PDFDoc(input_path + input_filename))
                {
                    doc.InitSecurityHandler();

                    ElementWriter writer  = new ElementWriter();
                    ElementReader reader  = new ElementReader();
                    XSet          visited = new XSet();

                    PageIterator itr = doc.GetPageIterator();

                    while (itr.HasNext())
                    {
                        try
                        {
                            Page page = itr.Current();
                            visited.Add(page.GetSDFObj().GetObjNum());

                            reader.Begin(page);
                            writer.Begin(page, ElementWriter.WriteMode.e_replacement, false, true, page.GetResourceDict());

                            ProcessElements(reader, writer, visited);
                            writer.End();
                            reader.End();

                            itr.Next();
                        }
                        catch (PDFNetException e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }

                    doc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_remove_unused);
                    Console.WriteLine("Done. Result saved in {0}...", output_filename);
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #9
0
        private static void WriteSingleDetail <T>(XmlTextWriter writer, string key, T detail)
        {
            var type = SerializationUtility.GetTypeAndAssemblyName(typeof(T));

            using (var td = new ElementWriter("li", writer))
            {
                td.WriteAttribute("data-key", key);
                td.WriteAttribute("data-type", type);
                try { td.WriteCData(detail.ToString()); }
                catch { td.Write("NULL"); }
            }
        }
Beispiel #10
0
 public void Add <TKey, TValue>(
     IDictionary <TKey, TValue> values,
     ElementWriter <TKey> keyWriter,
     ElementWriter <TValue> valueWriter
     ) where TKey : notnull
 => AddArray(() =>
 {
     foreach (var value in values)
     {
         StartCompoundValue();
         keyWriter(value.Key);
         valueWriter(value.Value);
     }
 }, storesCompoundValues: true);
Beispiel #11
0
        /// <summary>
        /// Writes a page out to the given XmlTextWriter
        /// </summary>
        /// <param name="item"></param>
        /// <param name="options"></param>
        /// <param name="writer"></param>
        public virtual void Write(ContentItem item, ExportOptions options, XmlTextWriter writer)
        {
            Debug.Assert(item.IsPage, "item.IsPage");
            using (var html = new ElementWriter("html", writer))
            {
                writer.WriteStartElement("head");
                writer.WriteEndElement();
                writer.WriteStartElement("body");

                WriteSingleItem(item, options, writer);

                WriteChildPartsWithZones(item, options, writer);
                writer.WriteEndElement(); // </body>
            }
        }
Beispiel #12
0
        public void AddArray(ElementWriter writer, bool storesCompoundValues)
        {
            ensureAlignment(4);
            var lengthSpan = MemoryMarshal.Cast <byte, int>(reserve(4));

            if (storesCompoundValues)
            {
                StartCompoundValue();
            }
            var arrayStart = index;

            writer();

            var arrayLength = index - arrayStart;

            lengthSpan[0] = arrayLength;
        }
        static PatternColor CreateTilingPattern(PDFDoc doc)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder eb = new ElementBuilder())
                {
                    // Create a new pattern content stream - a heart. ------------
                    writer.Begin(doc);
                    eb.PathBegin();
                    eb.MoveTo(0, 0);
                    eb.CurveTo(500, 500, 125, 625, 0, 500);
                    eb.CurveTo(-125, 625, -500, 500, 0, 0);
                    Element heart = eb.PathEnd();
                    heart.SetPathFill(true);

                    // Set heart color to red.
                    heart.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                    heart.GetGState().SetFillColor(new ColorPt(1, 0, 0));
                    writer.WriteElement(heart);

                    Obj pattern_dict = writer.End();

                    // Initialize pattern dictionary. For details on what each parameter represents please
                    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
                    pattern_dict.PutName("Type", "Pattern");
                    pattern_dict.PutNumber("PatternType", 1);

                    // TilingType - Constant spacing.
                    pattern_dict.PutNumber("TilingType", 1);

                    // This is a Type1 pattern - A colored tiling pattern.
                    pattern_dict.PutNumber("PaintType", 1);

                    // Set bounding box
                    pattern_dict.PutRect("BBox", -253, 0, 253, 545);

                    // Set the pattern matrix
                    pattern_dict.PutMatrix("Matrix", new Matrix2D(0.04, 0, 0, 0.04, 0, 0));

                    // Set the desired horizontal and vertical spacing between pattern cells,
                    // measured in the pattern coordinate system.
                    pattern_dict.PutNumber("XStep", 1000);
                    pattern_dict.PutNumber("YStep", 1000);

                    return(new PatternColor(pattern_dict));            // finished creating the Pattern resource
                }
        }
        // Creates some content (a path in the shape of a heart) and associate it with the vector layer
        static Obj CreateGroup2(PDFDoc doc, Obj layer)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder builder = new ElementBuilder())
                {
                    writer.Begin(doc);

                    // Create a path object in the shape of a heart.
                    builder.PathBegin();                        // start constructing the path
                    builder.MoveTo(306, 396);
                    builder.CurveTo(681, 771, 399.75, 864.75, 306, 771);
                    builder.CurveTo(212.25, 864.75, -69, 771, 306, 396);
                    builder.ClosePath();
                    Element element = builder.PathEnd();             // the path geometry is now specified.

                    // Set the path FILL color space and color.
                    element.SetPathFill(true);
                    GState gstate = element.GetGState();
                    gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK());
                    gstate.SetFillColor(new ColorPt(1, 0, 0, 0));              // cyan

                    // Set the path STROKE color space and color.
                    element.SetPathStroke(true);
                    gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB());
                    gstate.SetStrokeColor(new ColorPt(1, 0, 0));              // red
                    gstate.SetLineWidth(20);

                    gstate.SetTransform(0.5, 0, 0, 0.5, 280, 300);

                    writer.WriteElement(element);

                    Obj grp_obj = writer.End();


                    // Indicate that this form (content group) belongs to the given layer (OCG).
                    grp_obj.PutName("Subtype", "Form");
                    grp_obj.Put("OC", layer);
                    grp_obj.PutRect("BBox", 0, 0, 1000, 1000);                  // Set the clip box for the content.

                    return(grp_obj);
                }
        }
        static Obj CreateCustomButtonAppearance(PDFDoc doc, bool button_down)
        {
            // Create a button appearance stream ------------------------------------
            using (ElementBuilder builder = new ElementBuilder())
                using (ElementWriter writer = new ElementWriter())
                {
                    writer.Begin(doc);

                    // Draw background
                    Element element = builder.CreateRect(0, 0, 101, 37);
                    element.SetPathFill(true);
                    element.SetPathStroke(false);
                    element.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceGray());
                    element.GetGState().SetFillColor(new ColorPt(0.75, 0.0, 0.0));
                    writer.WriteElement(element);

                    // Draw 'Submit' text
                    writer.WriteElement(builder.CreateTextBegin());

                    element = builder.CreateTextRun("Submit", Font.Create(doc, Font.StandardType1Font.e_helvetica_bold), 12);
                    element.GetGState().SetFillColor(new ColorPt(0, 0, 0));

                    if (button_down)
                    {
                        element.SetTextMatrix(1, 0, 0, 1, 33, 10);
                    }
                    else
                    {
                        element.SetTextMatrix(1, 0, 0, 1, 30, 13);
                    }
                    writer.WriteElement(element);
                    writer.WriteElement(builder.CreateTextEnd());

                    Obj stm = writer.End();

                    // Set the bounding box
                    stm.PutRect("BBox", 0, 0, 101, 37);
                    stm.PutName("Subtype", "Form");
                    return(stm);
                }
        }
Beispiel #16
0
        public void Write(XmlWriter writer, Path path)
        {
            if (!path.Visible)
            {
                return;
            }

            writer.WriteStartElement("g");

            var elementWriter = new ElementWriter {
                GenerationOptions = GenerationOptions
            };

            elementWriter.WriteAttributes(writer, path);
            WriteAttributes(writer, path);

            elementWriter.WriteSubElements(writer, path);
            WriteSubElements(writer, path);

            writer.WriteEndElement();
        }
Beispiel #17
0
    public static IList<ListCompare> TwoWayDiff(string baseXml, string compareXml, out string baseFormatted, out string compareFormatted)
    {
      var baseElem = GetFirstItemElem(XElement.Parse(baseXml));
      baseElem = baseElem.Parent ?? baseElem;
      var compareElem = GetFirstItemElem(XElement.Parse(compareXml));
      compareElem = compareElem.Parent ?? compareElem;
      var settings = new XmlWriterSettings();
      settings.Indent = true;
      settings.IndentChars = "  ";
      settings.OmitXmlDeclaration = true;
      settings.NewLineOnAttributes = false;

      var baseWriter = new ElementWriter(settings);
      baseWriter.WriteStartElement(baseElem);

      var compareWriter = new ElementWriter(settings);
      compareWriter.WriteStartElement(compareElem);

      var results = new List<ListCompare>();
      if (!baseElem.Elements().Any() || !baseElem.Elements().Any())
      {
        var isDifferent = baseElem.Elements().Any()
          || baseElem.Elements().Any()
          || GetKeys(Enumerable.Repeat(baseElem, 1)).Single().Item1 != GetKeys(Enumerable.Repeat(compareElem, 1)).Single().Item1;
        results.Add(new ListCompare(baseWriter.CurrentLine + 1, compareWriter.CurrentLine + 1) { IsDifferent = isDifferent });
      }
      else
      {
        results.Add(new ListCompare(baseWriter.CurrentLine + 1, compareWriter.CurrentLine + 1) { IsDifferent = false });
        TwoWayDiff(baseElem, compareElem, baseWriter, compareWriter, results);
      }

      baseWriter.WriteEndElement();
      baseFormatted = baseWriter.ToString();
      compareWriter.WriteEndElement();
      compareFormatted = compareWriter.ToString();
      return results;
    }
Beispiel #18
0
        public virtual void Write(TextWriter output, IFeed feed)
        {
            XmlTextWriter xtw = new XmlTextWriter(output);

            xtw.Formatting = Formatting.Indented;
            xtw.WriteStartDocument();

            using (ElementWriter rssElement = new ElementWriter("rss", xtw))
            {
                rssElement.WriteAttribute("version", "2.0");
                rssElement.WriteAttribute("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
                using (new ElementWriter("channel", xtw))
                {
                    IEnumerable <ISyndicatable> items = feed.GetItems();
                    WriteChannelInfo(xtw, feed);
                    foreach (ISyndicatable item in items)
                    {
                        WriteItem(item, xtw);
                    }
                }
            }
            xtw.WriteEndDocument();
        }
Beispiel #19
0
        public virtual void WriteChildPartsWithZones(ContentItem item, ExportOptions options, XmlTextWriter writer)
        {
            var itemsInZones = item.Children.GroupBy(x => x.ZoneName);

            foreach (var zone in itemsInZones)
            {
                using (var zoneElement = new ElementWriter("section", writer))
                {
                    zoneElement.WriteAttribute("class", "zone");
                    zoneElement.WriteAttribute("id", zone.Key);

                    foreach (var childItem in zone)
                    {
                        using (var partElement = new ElementWriter("part", writer))
                        {
                            partElement.WriteAttribute("id", childItem.ID);
                            WriteSingleItem(childItem, options, writer);
                            WriteChildPartsWithZones(childItem, options, writer); // recursively until there are no more zones
                        }
                    }
                }
            }
        }
        static Obj CreateHighlightAppearance(List <Rect> boxes, ColorPt highlightColor, double highlightOpacity, Document document)
        {
            var elementBuilder = new ElementBuilder();

            elementBuilder.PathBegin();

            boxes.ForEach(box => elementBuilder.Rect(box.x1 - 2, box.y1, box.x2 - box.x1, box.y2 - box.y1));

            Element element = elementBuilder.PathEnd();

            element.SetPathFill(true);
            element.SetPathStroke(false);

            GState elementGraphicState = element.GetGState();

            elementGraphicState.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
            elementGraphicState.SetFillColor(highlightColor);
            elementGraphicState.SetFillOpacity(highlightOpacity);
            elementGraphicState.SetBlendMode(GState.BlendMode.e_bl_multiply);

            var elementWriter = new ElementWriter();

            elementWriter.Begin(document);

            elementWriter.WriteElement(element);
            Obj highlightAppearance = elementWriter.End();

            elementBuilder.Dispose();
            elementWriter.Dispose();

            Rect boundingBox = RectangleUnion(boxes);

            highlightAppearance.PutRect("BBox", boundingBox.x1, boundingBox.y1, boundingBox.x2, boundingBox.y2);
            highlightAppearance.PutName("Subtype", "Form");

            return(highlightAppearance);
        }
        static PatternColor CreateImageTilingPattern(PDFDoc doc)
        {
            using (ElementWriter writer = new ElementWriter())
                using (ElementBuilder eb = new ElementBuilder())
                {
                    // Create a new pattern content stream - a single bitmap object ----------
                    writer.Begin(doc);
                    Image   img         = Image.Create(doc, input_path + "butterfly.png");
                    Element img_element = eb.CreateImage(img, 0, 0, img.GetImageWidth(), img.GetImageHeight());
                    writer.WritePlacedElement(img_element);
                    Obj pattern_dict = writer.End();

                    // Initialize pattern dictionary. For details on what each parameter represents please
                    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
                    pattern_dict.PutName("Type", "Pattern");
                    pattern_dict.PutNumber("PatternType", 1);

                    // TilingType - Constant spacing.
                    pattern_dict.PutNumber("TilingType", 1);

                    // This is a Type1 pattern - A colored tiling pattern.
                    pattern_dict.PutNumber("PaintType", 1);

                    // Set bounding box
                    pattern_dict.PutRect("BBox", -253, 0, 253, 545);

                    // Set the pattern matrix
                    pattern_dict.PutMatrix("Matrix", new Matrix2D(0.3, 0, 0, 0.3, 0, 0));

                    // Set the desired horizontal and vertical spacing between pattern cells,
                    // measured in the pattern coordinate system.
                    pattern_dict.PutNumber("XStep", 300);
                    pattern_dict.PutNumber("YStep", 300);

                    return(new PatternColor(pattern_dict));            // finished creating the Pattern resource
                }
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();
            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementWriter writer = new ElementWriter())
                        using (ElementBuilder eb = new ElementBuilder())
                        {
                            // The following sample illustrates how to create and use tiling patterns
                            Page page = doc.PageCreate();
                            writer.Begin(page);

                            Element element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_bold), 1);
                            writer.WriteElement(element);              // Begin the text block

                            element = eb.CreateTextRun("G");
                            element.SetTextMatrix(720, 0, 0, 720, 20, 240);
                            GState gs = element.GetGState();
                            gs.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text);
                            gs.SetLineWidth(4);

                            // Set the fill color space to the Pattern color space.
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateTilingPattern(doc));

                            writer.WriteElement(element);
                            writer.WriteElement(eb.CreateTextEnd()); // Finish the text block

                            writer.End();                            // Save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            /// The following sample illustrates how to create and use image tiling pattern
                            page = doc.PageCreate();
                            writer.Begin(page);

                            eb.Reset();
                            element = eb.CreateRect(0, 0, 612, 794);

                            // Set the fill color space to the Pattern color space.
                            gs = element.GetGState();
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateImageTilingPattern(doc));
                            element.SetPathFill(true);

                            writer.WriteElement(element);

                            writer.End();               // Save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            /// The following sample illustrates how to create and use PDF shadings
                            page = doc.PageCreate();
                            writer.Begin(page);

                            eb.Reset();
                            element = eb.CreateRect(0, 0, 612, 794);

                            // Set the fill color space to the Pattern color space.
                            gs = element.GetGState();
                            gs.SetFillColorSpace(ColorSpace.CreatePattern());
                            gs.SetFillColor(CreateAxialShading(doc));
                            element.SetPathFill(true);

                            writer.WriteElement(element);

                            writer.End();               // save the page
                            doc.PagePushBack(page);
                            //-----------------------------------------------

                            doc.Save(output_path + "patterns.pdf", SDFDoc.SaveOptions.e_remove_unused);
                            Console.WriteLine("Done. Result saved in patterns.pdf...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="writer"></param>
 /// <author>
 /// Created by Iulian Iuga; 27 December, 2002
 /// </author>
 public virtual void Render(HtmlTextWriter writer)           //, TreeRenderState treeState
 {
     ElementWriter.RenderElement(writer, this);
 }
Beispiel #24
0
        /// <summary>
        /// Write an array.
        /// </summary>
        /// <typeparam name="T">Array element type.</typeparam>
        /// <param name="name">Array name.</param>
        /// <param name="value">The array to write.</param>
        /// <param name="nullable">if set to <c>true</c> [nullable].</param>
        /// <param name="rank">The rank (dimension) of array.</param>
        /// <param name="elementWriter">A callback function that writes the primitive type elements.
        /// If this is null, the elements will be written as object using function void Write(string name, bool nullable, ISerializable value).</param>
        private void WriteArray <T>(string name, object value, bool nullable, uint rank, ElementWriter <T> elementWriter)
        {
            if (rank == 0)
            {
                throw new ArgumentException("rank");
            }

            this.WriteNullableFlag(value, nullable);
            if (value == null)
            {
                return;
            }

            if (rank == 1)
            {
                var arr = value as ICollection <T>;
                if (arr == null)
                {
                    throw new TeslaSerializationException("A non-sequence value is serialized as array. Sequence type must implement ICollection and ICollection<T>. The actual type is " + value.GetType().FullName + " T: " + typeof(T).FullName + ", rank: 1");
                }

                // Write number of elements.
                this.WriteVInt((ulong)arr.Count);

                if (elementWriter == null)
                {
                    // Write object elements.
                    foreach (var element in arr)
                    {
                        if (element is ISerializable)
                        {
                            Write(null, (ISerializable)element, false);
                        }
                        else
                        {
                            throw new TeslaSerializationException("An object that doesn't implement ISerializable was found in array.");
                        }
                    }
                }
                else
                {
                    // Write primitive type elements.
                    foreach (var element in arr)
                    {
                        elementWriter(null, element);
                    }
                }
            }
            else
            {
                // Multiple dimensional arrays.
                var arr = value as ICollection;
                if (arr == null)
                {
                    throw new TeslaSerializationException("A non-sequence value is serialized as multiple dimensional array. Sequence type must implement ICollection and ICollection<T>");
                }

                // Write number of elements.
                this.WriteVInt((ulong)arr.Count);

                foreach (var subArr in arr)
                {
                    this.WriteArray(null, subArr, false, rank - 1, elementWriter);
                }
            }
        }
        static void ProcessElements(ElementReader reader, ElementWriter writer, XSet visited)
        {
            Element element;

            while ((element = reader.Next()) != null)             // Read page contents
            {
                switch (element.GetType())
                {
                case Element.Type.e_image:
                case Element.Type.e_inline_image:
                    // remove all images by skipping them
                    break;

                case Element.Type.e_path:
                {
                    // Set all paths to red color.
                    GState gs = element.GetGState();
                    gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                    gs.SetFillColor(new ColorPt(1, 0, 0));
                    writer.WriteElement(element);
                    break;
                }

                case Element.Type.e_text:
                {
                    // Set all text to blue color.
                    GState gs = element.GetGState();
                    gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                    gs.SetFillColor(new ColorPt(0, 0, 1));
                    writer.WriteElement(element);
                    break;
                }

                case Element.Type.e_form:
                {
                    writer.WriteElement(element);                                     // write Form XObject reference to current stream

                    Obj form_obj = element.GetXObject();
                    if (!visited.Contains(form_obj.GetObjNum()))                                     // if this XObject has not been processed
                    {
                        // recursively process the Form XObject
                        visited.Add(form_obj.GetObjNum());
                        ElementWriter new_writer = new ElementWriter();

                        reader.FormBegin();
                        new_writer.Begin(form_obj, true);

                        reader.ClearChangeList();
                        new_writer.SetDefaultGState(reader);

                        ProcessElements(reader, new_writer, visited);
                        new_writer.End();
                        reader.End();
                    }
                    break;
                }

                default:
                    writer.WriteElement(element);
                    break;
                }
            }
        }
        /// <summary>
        //-----------------------------------------------------------------------------------
        // This sample illustrates how to embed various raster image formats
        // (e.g. TIFF, JPEG, JPEG2000, JBIG2, GIF, PNG, BMP, etc.) in a PDF document.
        //-----------------------------------------------------------------------------------
        /// </summary>
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementBuilder bld = new ElementBuilder())      // Used to build new Element objects
                        using (ElementWriter writer = new ElementWriter()) // Used to write Elements to the page
                        {
                            Page page = doc.PageCreate();                  // Start a new page
                            writer.Begin(page);                            // Begin writing to this page

                            // ----------------------------------------------------------
                            // Embed a JPEG image to the output document.
                            Image img = Image.Create(doc, input_path + "peppers.jpg");

                            // You can also directly add any .NET Bitmap. The following commented-out code
                            // is equivalent to the above line:
                            //    System.Drawing.Bitmap bmp;
                            //    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(input_path + "peppers.jpg");
                            //    Image img = Image.Create(doc, bmp);

                            Element element = bld.CreateImage(img, 50, 500, img.GetImageWidth() / 2, img.GetImageHeight() / 2);
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a PNG image to the output file
                            img     = Image.Create(doc, input_path + "butterfly.png");
                            element = bld.CreateImage(img, new Matrix2D(100, 0, 0, 100, 300, 500));
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a GIF image to the output file
                            img     = Image.Create(doc, input_path + "pdfnet.gif");
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 50, 350));
                            writer.WritePlacedElement(element);

                            // ----------------------------------------------------------
                            // Add a TIFF image to the output file
                            img     = Image.Create(doc, input_path + "grayscale.tif");
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 10, 50));
                            writer.WritePlacedElement(element);

                            writer.End();           // Save the page
                            doc.PagePushBack(page); // Add the page to the document page sequence

                            // ----------------------------------------------------------
                            // Add a BMP image to the output file

                            /*
                             * bmp = new System.Drawing.Bitmap(input_path + "pdftron.bmp");
                             *                  img = Image.Create(doc, bmp);
                             *                  element = bld.CreateImage(img, new Matrix2D(bmp.Width, 0, 0, bmp.Height, 255, 700));
                             *                  writer.WritePlacedElement(element);
                             *
                             *                  writer.End();	// Finish writing to the page
                             *                  doc.PagePushBack(page);
                             */

                            // ----------------------------------------------------------
                            // Embed a monochrome TIFF. Compress the image using lossy JBIG2 filter.

                            page = doc.PageCreate(new pdftron.PDF.Rect(0, 0, 612, 794));
                            writer.Begin(page); // begin writing to this page

                            // Note: encoder hints can be used to select between different compression methods.
                            // For example to instruct PDFNet to compress a monochrome image using JBIG2 compression.
                            ObjSet hint_set = new ObjSet();
                            Obj    enc      = hint_set.CreateArray(); // Initialize encoder 'hint' parameter
                            enc.PushBackName("JBIG2");
                            enc.PushBackName("Lossy");

                            img     = pdftron.PDF.Image.Create(doc, input_path + "multipage.tif", enc);
                            element = bld.CreateImage(img, new Matrix2D(612, 0, 0, 794, 0, 0));
                            writer.WritePlacedElement(element);

                            writer.End();           // Save the page
                            doc.PagePushBack(page); // Add the page to the document page sequence

                            // ----------------------------------------------------------
                            // Add a JPEG2000 (JP2) image to the output file

                            // Create a new page
                            page = doc.PageCreate();
                            writer.Begin(page); // Begin writing to the page

                            // Embed the image.
                            img = pdftron.PDF.Image.Create(doc, input_path + "palm.jp2");

                            // Position the image on the page.
                            element = bld.CreateImage(img, new Matrix2D(img.GetImageWidth(), 0, 0, img.GetImageHeight(), 96, 80));
                            writer.WritePlacedElement(element);

                            // Write 'JPEG2000 Sample' text string under the image.
                            writer.WriteElement(bld.CreateTextBegin(pdftron.PDF.Font.Create(doc, pdftron.PDF.Font.StandardType1Font.e_times_roman), 32));
                            element = bld.CreateTextRun("JPEG2000 Sample");
                            element.SetTextMatrix(1, 0, 0, 1, 190, 30);
                            writer.WriteElement(element);
                            writer.WriteElement(bld.CreateTextEnd());

                            writer.End(); // Finish writing to the page
                            doc.PagePushBack(page);


                            doc.Save(output_path + "addimage.pdf", SDFDoc.SaveOptions.e_linearized);
                            Console.WriteLine("Done. Result saved in addimage.pdf...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            // The first step in every application using PDFNet is to initialize the
            // library and set the path to common PDF resources. The library is usually
            // initialized only once, but calling Initialize() multiple times is also fine.
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            try
            {
                // Open the PDF document.
                using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                    using (ElementBuilder bld = new ElementBuilder())      // Used to build new Element objects
                        using (ElementWriter writer = new ElementWriter()) // Used to write Elements to the page
                        {
                            UndoManager undo_manager = doc.GetUndoManager();

                            // Take a snapshot to which we can undo after making changes.
                            ResultSnapshot snap0 = undo_manager.TakeSnapshot();

                            DocSnapshot snap0_state = snap0.CurrentState();

                            Page page = doc.PageCreate(); // Start a new page

                            writer.Begin(page);           // Begin writing to this page

                            // ----------------------------------------------------------
                            // Add JPEG image to the file
                            Image   img     = Image.Create(doc, input_path + "peppers.jpg");
                            Element element = bld.CreateImage(img, new Matrix2D(200, 0, 0, 250, 50, 500));
                            writer.WritePlacedElement(element);

                            writer.End(); // Finish writing to the page
                            doc.PagePushFront(page);

                            // Take a snapshot after making changes, so that we can redo later (after undoing first).
                            ResultSnapshot snap1 = undo_manager.TakeSnapshot();

                            if (snap1.PreviousState().Equals(snap0_state))
                            {
                                Console.WriteLine("snap1 previous state equals snap0_state; previous state is correct");
                            }

                            DocSnapshot snap1_state = snap1.CurrentState();

                            doc.Save(output_path + "addimage.pdf", SDFDoc.SaveOptions.e_incremental);

                            if (undo_manager.CanUndo())
                            {
                                ResultSnapshot undo_snap = undo_manager.Undo();

                                doc.Save(output_path + "addimage_undone.pdf", SDFDoc.SaveOptions.e_incremental);

                                DocSnapshot undo_snap_state = undo_snap.CurrentState();

                                if (undo_snap_state.Equals(snap0_state))
                                {
                                    Console.WriteLine("undo_snap_state equals snap0_state; undo was successful");
                                }

                                if (undo_manager.CanRedo())
                                {
                                    ResultSnapshot redo_snap = undo_manager.Redo();

                                    doc.Save(output_path + "addimage_redone.pdf", SDFDoc.SaveOptions.e_incremental);

                                    if (redo_snap.PreviousState().Equals(undo_snap_state))
                                    {
                                        Console.WriteLine("redo_snap previous state equals undo_snap_state; previous state is correct");
                                    }

                                    DocSnapshot redo_snap_state = redo_snap.CurrentState();

                                    if (redo_snap_state.Equals(snap1_state))
                                    {
                                        Console.WriteLine("Snap1 and redo_snap are equal; redo was successful");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Problem encountered - cannot redo.");
                                }
                            }
                            else
                            {
                                Console.WriteLine("Problem encountered - cannot undo.");
                            }
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";


            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementBuilder eb = new ElementBuilder())                    // ElementBuilder is used to build new Element objects
                        using (ElementWriter writer = new ElementWriter())              // ElementWriter is used to write Elements to the page
                        {
                            // Start a new page ------------------------------------
                            // Position an image stream on several places on the page
                            Page page = doc.PageCreate(new Rect(0, 0, 612, 794));

                            writer.Begin(page);                 // begin writing to this page

                            // Create an Image that can be reused multiple times in the document or
                            // multiple on the same page.
                            MappedFile   img_file = new MappedFile(input_path + "peppers.jpg");
                            FilterReader img_data = new FilterReader(img_file);
                            Image        img      = Image.Create(doc, img_data, 400, 600, 8, ColorSpace.CreateDeviceRGB(), Image.InputFilter.e_jpeg);

                            Element element = eb.CreateImage(img, new Matrix2D(200, -145, 20, 300, 200, 150));
                            writer.WritePlacedElement(element);

                            GState gstate = element.GetGState();                // use the same image (just change its matrix)
                            gstate.SetTransform(200, 0, 0, 300, 50, 450);
                            writer.WritePlacedElement(element);

                            // use the same image again (just change its matrix).
                            writer.WritePlacedElement(eb.CreateImage(img, 300, 600, 200, -150));

                            writer.End();              // save changes to the current page
                            doc.PagePushBack(page);

                            // Start a new page ------------------------------------
                            // Construct and draw a path object using different styles
                            page = doc.PageCreate(new Rect(0, 0, 612, 794));

                            writer.Begin(page);                 // begin writing to this page
                            eb.Reset();                         // Reset GState to default


                            eb.PathBegin();                     // start constructing the path
                            eb.MoveTo(306, 396);
                            eb.CurveTo(681, 771, 399.75, 864.75, 306, 771);
                            eb.CurveTo(212.25, 864.75, -69, 771, 306, 396);
                            eb.ClosePath();
                            element = eb.PathEnd();                             // the path is now finished
                            element.SetPathFill(true);                          // the path should be filled

                            // Set the path color space and color
                            gstate = element.GetGState();
                            gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK());
                            gstate.SetFillColor(new ColorPt(1, 0, 0, 0));              // cyan
                            gstate.SetTransform(0.5, 0, 0, 0.5, -20, 300);
                            writer.WritePlacedElement(element);

                            // Draw the same path using a different stroke color
                            element.SetPathStroke(true);                        // this path is should be filled and stroked
                            gstate.SetFillColor(new ColorPt(0, 0, 1, 0));       // yellow
                            gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB());
                            gstate.SetStrokeColor(new ColorPt(1, 0, 0));        // red
                            gstate.SetTransform(0.5, 0, 0, 0.5, 280, 300);
                            gstate.SetLineWidth(20);
                            writer.WritePlacedElement(element);

                            // Draw the same path with with a given dash pattern
                            element.SetPathFill(false);                  // this path is should be only stroked
                            gstate.SetStrokeColor(new ColorPt(0, 0, 1)); // blue
                            gstate.SetTransform(0.5, 0, 0, 0.5, 280, 0);
                            double[] dash_pattern = { 30 };
                            gstate.SetDashPattern(dash_pattern, 0);
                            writer.WritePlacedElement(element);

                            // Use the path as a clipping path
                            writer.WriteElement(eb.CreateGroupBegin());                 // Save the graphics state
                            // Start constructing a new path (the old path was lost when we created
                            // a new Element using CreateGroupBegin()).
                            eb.PathBegin();
                            eb.MoveTo(306, 396);
                            eb.CurveTo(681, 771, 399.75, 864.75, 306, 771);
                            eb.CurveTo(212.25, 864.75, -69, 771, 306, 396);
                            eb.ClosePath();
                            element = eb.PathEnd();             // path is now built
                            element.SetPathClip(true);          // this path is a clipping path
                            element.SetPathStroke(true);        // this path is should be filled and stroked
                            gstate = element.GetGState();
                            gstate.SetTransform(0.5, 0, 0, 0.5, -20, 0);
                            writer.WriteElement(element);
                            writer.WriteElement(eb.CreateImage(img, 100, 300, 400, 600));
                            writer.WriteElement(eb.CreateGroupEnd()); // Restore the graphics state

                            writer.End();                             // save changes to the current page
                            doc.PagePushBack(page);


                            // Start a new page ------------------------------------
                            page = doc.PageCreate(new Rect(0, 0, 612, 794));

                            writer.Begin(page);                 // begin writing to this page
                            eb.Reset();                         // Reset GState to default

                            // Begin writing a block of text
                            element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12);
                            writer.WriteElement(element);

                            string data = "Hello World!";
                            element = eb.CreateTextRun(data);
                            element.SetTextMatrix(10, 0, 0, 10, 0, 600);
                            element.GetGState().SetLeading(15);                          // Set the spacing between lines
                            writer.WriteElement(element);

                            writer.WriteElement(eb.CreateTextNewLine());              // New line

                            element = eb.CreateTextRun(data);
                            gstate  = element.GetGState();
                            gstate.SetTextRenderMode(GState.TextRenderingMode.e_stroke_text);
                            gstate.SetCharSpacing(-1.25);
                            gstate.SetWordSpacing(-1.25);
                            writer.WriteElement(element);

                            writer.WriteElement(eb.CreateTextNewLine());              // New line

                            element = eb.CreateTextRun(data);
                            gstate  = element.GetGState();
                            gstate.SetCharSpacing(0);
                            gstate.SetWordSpacing(0);
                            gstate.SetLineWidth(3);
                            gstate.SetTextRenderMode(GState.TextRenderingMode.e_fill_stroke_text);
                            gstate.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB());
                            gstate.SetStrokeColor(new ColorPt(1, 0, 0));                // red
                            gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK());
                            gstate.SetFillColor(new ColorPt(1, 0, 0, 0));               // cyan
                            writer.WriteElement(element);

                            writer.WriteElement(eb.CreateTextNewLine());              // New line

                            // Set text as a clipping path to the image.
                            element = eb.CreateTextRun(data);
                            gstate  = element.GetGState();
                            gstate.SetTextRenderMode(GState.TextRenderingMode.e_clip_text);
                            writer.WriteElement(element);

                            // Finish the block of text
                            writer.WriteElement(eb.CreateTextEnd());

                            // Draw an image that will be clipped by the above text
                            writer.WriteElement(eb.CreateImage(img, 10, 100, 1300, 720));

                            writer.End();              // save changes to the current page
                            doc.PagePushBack(page);

                            // Start a new page ------------------------------------
                            //
                            // The example illustrates how to embed the external font in a PDF document.
                            // The example also shows how ElementReader can be used to copy and modify
                            // Elements between pages.

                            using (ElementReader reader = new ElementReader())
                            {
                                // Start reading Elements from the last page. We will copy all Elements to
                                // a new page but will modify the font associated with text.
                                reader.Begin(doc.GetPage(doc.GetPageCount()));

                                page = doc.PageCreate(new Rect(0, 0, 1300, 794));

                                writer.Begin(page);                     // begin writing to this page
                                eb.Reset();                             // Reset GState to default

                                // Embed an external font in the document.
                                Font font = Font.CreateTrueTypeFont(doc, input_path + "font.ttf");

                                while ((element = reader.Next()) != null)                       // Read page contents
                                {
                                    if (element.GetType() == Element.Type.e_text)
                                    {
                                        element.GetGState().SetFont(font, 12);
                                    }

                                    writer.WriteElement(element);
                                }

                                reader.End();
                                writer.End();                  // save changes to the current page

                                doc.PagePushBack(page);


                                // Start a new page ------------------------------------
                                //
                                // The example illustrates how to embed the external font in a PDF document.
                                // The example also shows how ElementReader can be used to copy and modify
                                // Elements between pages.

                                // Start reading Elements from the last page. We will copy all Elements to
                                // a new page but will modify the font associated with text.
                                reader.Begin(doc.GetPage(doc.GetPageCount()));

                                page = doc.PageCreate(new Rect(0, 0, 1300, 794));

                                writer.Begin(page);                     // begin writing to this page
                                eb.Reset();                             // Reset GState to default

                                // Embed an external font in the document.
                                Font font2 = Font.CreateType1Font(doc, input_path + "Misc-Fixed.pfa");

                                while ((element = reader.Next()) != null)                       // Read page contents
                                {
                                    if (element.GetType() == Element.Type.e_text)
                                    {
                                        element.GetGState().SetFont(font2, 12);
                                    }

                                    writer.WriteElement(element);
                                }

                                reader.End();
                                writer.End();                  // save changes to the current page
                                doc.PagePushBack(page);


                                // Start a new page ------------------------------------
                                page = doc.PageCreate();
                                writer.Begin(page);                     // begin writing to this page
                                eb.Reset();                             // Reset GState to default

                                // Begin writing a block of text
                                element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 12);
                                element.SetTextMatrix(1.5, 0, 0, 1.5, 50, 600);
                                element.GetGState().SetLeading(15);                     // Set the spacing between lines
                                writer.WriteElement(element);

                                string para = "A PDF text object consists of operators that can show " +
                                              "text strings, move the text position, and set text state and certain " +
                                              "other parameters. In addition, there are three parameters that are " +
                                              "defined only within a text object and do not persist from one text " +
                                              "object to the next: Tm, the text matrix, Tlm, the text line matrix, " +
                                              "Trm, the text rendering matrix, actually just an intermediate result " +
                                              "that combines the effects of text state parameters, the text matrix " +
                                              "(Tm), and the current transformation matrix";

                                int para_end = para.Length;
                                int text_run = 0;
                                int text_run_end;

                                double para_width = 300;                 // paragraph width is 300 units
                                double cur_width  = 0;

                                while (text_run < para_end)
                                {
                                    text_run_end = para.IndexOf(' ', text_run);
                                    if (text_run_end < 0)
                                    {
                                        text_run_end = para_end - 1;
                                    }

                                    string text = para.Substring(text_run, text_run_end - text_run + 1);
                                    element = eb.CreateTextRun(text);
                                    if (cur_width + element.GetTextLength() < para_width)
                                    {
                                        writer.WriteElement(element);
                                        cur_width += element.GetTextLength();
                                    }
                                    else
                                    {
                                        writer.WriteElement(eb.CreateTextNewLine());                          // New line
                                        text      = para.Substring(text_run, text_run_end - text_run + 1);
                                        element   = eb.CreateTextRun(text);
                                        cur_width = element.GetTextLength();
                                        writer.WriteElement(element);
                                    }

                                    text_run = text_run_end + 1;
                                }

                                // -----------------------------------------------------------------------
                                // The following code snippet illustrates how to adjust spacing between
                                // characters (text runs).
                                element = eb.CreateTextNewLine();
                                writer.WriteElement(element); // Skip 2 lines
                                writer.WriteElement(element);

                                writer.WriteElement(eb.CreateTextRun("An example of space adjustments between inter-characters:"));
                                writer.WriteElement(eb.CreateTextNewLine());

                                // Write string "AWAY" without space adjustments between characters.
                                element = eb.CreateTextRun("AWAY");
                                writer.WriteElement(element);

                                writer.WriteElement(eb.CreateTextNewLine());

                                // Write string "AWAY" with space adjustments between characters.
                                element = eb.CreateTextRun("A");
                                writer.WriteElement(element);

                                element = eb.CreateTextRun("W");
                                element.SetPosAdjustment(140);
                                writer.WriteElement(element);

                                element = eb.CreateTextRun("A");
                                element.SetPosAdjustment(140);
                                writer.WriteElement(element);

                                element = eb.CreateTextRun("Y again");
                                element.SetPosAdjustment(115);
                                writer.WriteElement(element);

                                // Draw the same strings using direct content output...
                                writer.Flush(); // flush pending Element writing operations.

                                // You can also write page content directly to the content stream using
                                // ElementWriter.WriteString(...) and ElementWriter.WriteBuffer(...) methods.
                                // Note that if you are planning to use these functions you need to be familiar
                                // with PDF page content operators (see Appendix A in PDF Reference Manual).
                                // Because it is easy to make mistakes during direct output we recommend that
                                // you use ElementBuilder and Element interface instead.
                                writer.WriteString("T* T* ");                 // New Lines
                                // writer.WriteElement(eb.CreateTextNewLine());
                                writer.WriteString("(Direct output to PDF page content stream:) Tj  T* ");
                                writer.WriteString("(AWAY) Tj T* ");
                                writer.WriteString("[(A)140(W)140(A)115(Y again)] TJ ");

                                // Finish the block of text
                                writer.WriteElement(eb.CreateTextEnd());

                                writer.End();                  // save changes to the current page
                                doc.PagePushBack(page);

                                // Start a new page ------------------------------------

                                // Image Masks
                                //
                                // In the opaque imaging model, images mark all areas they occupy on the page as
                                // if with opaque paint. All portions of the image, whether black, white, gray,
                                // or color, completely obscure any marks that may previously have existed in the
                                // same place on the page.
                                // In the graphic arts industry and page layout applications, however, it is common
                                // to crop or 'mask out' the background of an image and then place the masked image
                                // on a different background, allowing the existing background to show through the
                                // masked areas. This sample illustrates how to use image masks.

                                page = doc.PageCreate();
                                writer.Begin(page); // begin writing to the page

                                // Create the Image Mask
                                MappedFile   imgf      = new MappedFile(input_path + "imagemask.dat");
                                FilterReader mask_read = new FilterReader(imgf);

                                ColorSpace device_gray = ColorSpace.CreateDeviceGray();
                                Image      mask        = Image.Create(doc, mask_read, 64, 64, 1, device_gray, Image.InputFilter.e_ascii_hex);

                                mask.GetSDFObj().PutBool("ImageMask", true);

                                element = eb.CreateRect(0, 0, 612, 794);
                                element.SetPathStroke(false);
                                element.SetPathFill(true);
                                element.GetGState().SetFillColorSpace(device_gray);
                                element.GetGState().SetFillColor(new ColorPt(0.8));
                                writer.WritePlacedElement(element);

                                element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 680));
                                element.GetGState().SetFillColor(new ColorPt(0.1));
                                writer.WritePlacedElement(element);

                                element.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                                element.GetGState().SetFillColor(new ColorPt(1, 0, 0));
                                element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 320, 680));
                                writer.WritePlacedElement(element);

                                element.GetGState().SetFillColor(new ColorPt(0, 1, 0));
                                element = eb.CreateImage(mask, new Matrix2D(200, 0, 0, -200, 40, 380));
                                writer.WritePlacedElement(element);

                                {
                                    // This sample illustrates Explicit Masking.
                                    img = Image.Create(doc, input_path + "peppers.jpg");

                                    // mask is the explicit mask for the primary (base) image
                                    img.SetMask(mask);

                                    element = eb.CreateImage(img, new Matrix2D(200, 0, 0, -200, 320, 380));
                                    writer.WritePlacedElement(element);
                                }

                                writer.End(); // save changes to the current page
                                doc.PagePushBack(page);

                                // Transparency sample ----------------------------------

                                // Start a new page -------------------------------------
                                page = doc.PageCreate();
                                writer.Begin(page);                     // begin writing to this page
                                eb.Reset();                             // Reset the GState to default

                                // Write some transparent text at the bottom of the page.
                                element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_times_roman), 100);

                                // Set the text knockout attribute. Text knockout must be set outside of
                                // the text group.
                                gstate = element.GetGState();
                                gstate.SetTextKnockout(false);
                                gstate.SetBlendMode(GState.BlendMode.e_bl_difference);
                                writer.WriteElement(element);

                                element = eb.CreateTextRun("Transparency");
                                element.SetTextMatrix(1, 0, 0, 1, 30, 30);
                                gstate = element.GetGState();
                                gstate.SetFillColorSpace(ColorSpace.CreateDeviceCMYK());
                                gstate.SetFillColor(new ColorPt(1, 0, 0, 0));

                                gstate.SetFillOpacity(0.5);
                                writer.WriteElement(element);

                                // Write the same text on top the old; shifted by 3 points
                                element.SetTextMatrix(1, 0, 0, 1, 33, 33);
                                gstate.SetFillColor(new ColorPt(0, 1, 0, 0));
                                gstate.SetFillOpacity(0.5);

                                writer.WriteElement(element);
                                writer.WriteElement(eb.CreateTextEnd());

                                // Draw three overlapping transparent circles.
                                eb.PathBegin();                         // start constructing the path
                                eb.MoveTo(459.223, 505.646);
                                eb.CurveTo(459.223, 415.841, 389.85, 343.04, 304.273, 343.04);
                                eb.CurveTo(218.697, 343.04, 149.324, 415.841, 149.324, 505.646);
                                eb.CurveTo(149.324, 595.45, 218.697, 668.25, 304.273, 668.25);
                                eb.CurveTo(389.85, 668.25, 459.223, 595.45, 459.223, 505.646);
                                element = eb.PathEnd();
                                element.SetPathFill(true);

                                gstate = element.GetGState();
                                gstate.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
                                gstate.SetFillColor(new ColorPt(0, 0, 1));                                     // Blue Circle

                                gstate.SetBlendMode(GState.BlendMode.e_bl_normal);
                                gstate.SetFillOpacity(0.5);
                                writer.WriteElement(element);

                                // Translate relative to the Blue Circle
                                gstate.SetTransform(1, 0, 0, 1, 113, -185);
                                gstate.SetFillColor(new ColorPt(0, 1, 0));                                     // Green Circle
                                gstate.SetFillOpacity(0.5);
                                writer.WriteElement(element);

                                // Translate relative to the Green Circle
                                gstate.SetTransform(1, 0, 0, 1, -220, 0);
                                gstate.SetFillColor(new ColorPt(1, 0, 0));                                     // Red Circle
                                gstate.SetFillOpacity(0.5);
                                writer.WriteElement(element);

                                writer.End();                  // save changes to the current page
                                doc.PagePushBack(page);

                                // End page ------------------------------------
                            }

                            doc.Save(output_path + "element_builder.pdf", SDFDoc.SaveOptions.e_remove_unused);
                            Console.WriteLine("Done. Result saved in element_builder.pdf...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #29
0
        public virtual void WriteSingleItem(ContentItem item, ExportOptions options, XmlTextWriter writer)
        {
            var authorizedRolesList = String.Join("|",
                                                  from x in item.AuthorizedRoles
                                                  let y = x.ToString()
                                                          select y);

            using (var properties = new ElementWriter("ul", writer))
            {
                properties.WriteAttribute("class", "n2-itemproperties");
                properties.WriteAttribute("id", "n2-item" + item.ID);
                WriteSingleDetail(writer, "id", item.ID);
                WriteSingleDetail(writer, "name", item.ID.ToString() == item.Name ? "" : item.Name);

                if (item.Parent != null)
                {
                    if (item.Parent.ID != 0)
                    {
                        WriteSingleDetail(writer, "parent", item.Parent.ID.ToString());
                    }
                    else
                    {
                        WriteSingleDetail(writer, "parent", item.Parent.VersionOf.ID.ToString());
                        if (item.Parent.GetVersionKey() != null)
                        {
                            WriteSingleDetail(writer, "parentVersionKey", item.Parent.GetVersionKey());
                        }
                    }
                }
                WriteSingleDetail(writer, "title", item.Title);
                WriteSingleDetail(writer, "zoneName", item.ZoneName);
                WriteSingleDetail(writer, "templateKey", item.TemplateKey);
                WriteSingleDetail(writer, "translationKey", item.TranslationKey ?? 0);
                WriteSingleDetail(writer, "state", item.State.ToString());
                WriteSingleDetail(writer, "created", item.Created);
                WriteSingleDetail(writer, "updated", item.Updated);
                WriteSingleDetail(writer, "published", item.Published);
                WriteSingleDetail(writer, "expires", item.Expires);
                WriteSingleDetail(writer, "sortOrder", item.SortOrder);
                WriteSingleDetail(writer, "url", item.Url);
                WriteSingleDetail(writer, "visible", item.Visible);
                WriteSingleDetail(writer, "savedBy", item.SavedBy);
                WriteSingleDetail(writer, "typeName", SerializationUtility.GetTypeAndAssemblyName(item.GetContentType()));
                WriteSingleDetail(writer, "discriminator", _definitions.GetDefinition(item).Discriminator);
                WriteSingleDetail(writer, "versionIndex", item.VersionIndex);
                WriteSingleDetail(writer, "ancestralTrail", item.AncestralTrail);
                WriteSingleDetail(writer, "alteredPermissions", item.AlteredPermissions.ToString());
                WriteSingleDetail(writer, "childState", item.ChildState.ToString());
                if (item.VersionOf.HasValue)
                {
                    Debug.Assert(item.VersionOf.ID != null, "item.VersionOf.ID != null");
                    WriteSingleDetail(writer, "versionOf", item.VersionOf.ID.Value);
                }

                WriteSingleDetail(writer, "authorizedRoles", authorizedRolesList);
                //WriteSingleDetail(writer, "Extension", item.Extension);
                //WriteSingleDetail(writer, "IconUrl", item.IconUrl);
                //WriteSingleDetail(writer, "IsExpired", item.IsExpired());
                //WriteSingleDetail(writer, "IsPage", item.IsPage);
                //WriteSingleDetail(writer, "Path", item.Path);


                //foreach (ContentDetail d in item.Details)
                //  using (var html = new ElementWriter(C_PROPERTYTAG, writer))
                //  {
                //      html.WriteAttribute("data-type", d.ValueTypeKey);
                //      html.WriteAttribute("data-name", d.Name);
                //      html.WriteCData(d.Value.ToString());
                //  }
            }

            dw.Write(item, writer);
            dww.Write(item, writer);
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            try
            {
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("Opening the input pdf...");
                using (PDFDoc in_doc = new PDFDoc(input_path + "newsletter.pdf"))
                {
                    in_doc.InitSecurityHandler();

                    // Create a list of pages to import from one PDF document to another.
                    ArrayList import_list = new ArrayList();
                    for (PageIterator itr = in_doc.GetPageIterator(); itr.HasNext(); itr.Next())
                    {
                        import_list.Add(itr.Current());
                    }

                    using (PDFDoc new_doc = new PDFDoc())                     //  Create a new document
                        using (ElementBuilder builder = new ElementBuilder())
                            using (ElementWriter writer = new ElementWriter())
                            {
                                ArrayList imported_pages = new_doc.ImportPages(import_list);

                                // Paper dimension for A3 format in points. Because one inch has
                                // 72 points, 11.69 inch 72 = 841.69 points
                                Rect   media_box = new Rect(0, 0, 1190.88, 841.69);
                                double mid_point = media_box.Width() / 2;

                                for (int i = 0; i < imported_pages.Count; ++i)
                                {
                                    // Create a blank new A3 page and place on it two pages from the input document.
                                    Page new_page = new_doc.PageCreate(media_box);
                                    writer.Begin(new_page);

                                    // Place the first page
                                    Page    src_page = (Page)imported_pages[i];
                                    Element element  = builder.CreateForm(src_page);

                                    double sc_x  = mid_point / src_page.GetPageWidth();
                                    double sc_y  = media_box.Height() / src_page.GetPageHeight();
                                    double scale = Math.Min(sc_x, sc_y);
                                    element.GetGState().SetTransform(scale, 0, 0, scale, 0, 0);
                                    writer.WritePlacedElement(element);

                                    // Place the second page
                                    ++i;
                                    if (i < imported_pages.Count)
                                    {
                                        src_page = (Page)imported_pages[i];
                                        element  = builder.CreateForm(src_page);
                                        sc_x     = mid_point / src_page.GetPageWidth();
                                        sc_y     = media_box.Height() / src_page.GetPageHeight();
                                        scale    = Math.Min(sc_x, sc_y);
                                        element.GetGState().SetTransform(scale, 0, 0, scale, mid_point, 0);
                                        writer.WritePlacedElement(element);
                                    }

                                    writer.End();
                                    new_doc.PagePushBack(new_page);
                                }
                                new_doc.Save(output_path + "newsletter_booklet.pdf", SDFDoc.SaveOptions.e_linearized);
                                Console.WriteLine("Done. Result saved in newsletter_booklet.pdf...");
                            }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n{0}", e);
            }
        }
Beispiel #31
0
    private static void TwoWayDiff(XElement baseElem, XElement compareElem, ElementWriter bWriter, ElementWriter cWriter, List<ListCompare> results)
    {
      var baseList = GetKeys(baseElem.Elements());
      var compareList = GetKeys(compareElem.Elements());

      var compares = ListCompare.Create(baseList, compareList, v => v.Item1);
      // Deal with the relationships of versionable items
      if (baseElem.Name.LocalName == "Relationships" && !compares.Any(c => c.Base >= 0 && c.Compare >= 0))
      {
        var baseRelateds = baseElem.Elements().Select(e => Tuple.Create(GetRelatedId(e), e)).ToList();
        var compareRelateds = compareElem.Elements().Select(e => Tuple.Create(GetRelatedId(e), e)).ToList();
        if (!baseRelateds.Any(t => string.IsNullOrEmpty(t.Item1))
          && !compareRelateds.Any(t => string.IsNullOrEmpty(t.Item1))
          && baseRelateds.Select(t => t.Item1).Distinct().Count() == baseRelateds.Count
          && compareRelateds.Select(t => t.Item1).Distinct().Count() == compareRelateds.Count)
        {
          compares = ListCompare.Create(baseRelateds, compareRelateds, v => v.Item1);
        }
      }

      int start;
      foreach (var tuple in compares)
      {
        if (tuple.Base < 0)
        {
          start = cWriter.CurrentLine + 1;
          cWriter.WriteElement(compareList[tuple.Compare].Item2);
          results.AddRange(Enumerable.Range(start, cWriter.CurrentLine - start + 1).Select(i => new ListCompare(-1, i)));
        }
        else if (tuple.Compare < 0)
        {
          start = bWriter.CurrentLine + 1;
          bWriter.WriteElement(baseList[tuple.Base].Item2);
          results.AddRange(Enumerable.Range(start, bWriter.CurrentLine - start + 1).Select(i => new ListCompare(i, -1)));
        }
        else if (baseList[tuple.Base].Item2.Elements().Any() &&
          compareList[tuple.Compare].Item2.Elements().Any())
        {
          results.Add(new ListCompare(bWriter.CurrentLine + 1, cWriter.CurrentLine + 1) { IsDifferent = false });
          bWriter.WriteStartElement(baseList[tuple.Base].Item2);
          cWriter.WriteStartElement(compareList[tuple.Compare].Item2);
          TwoWayDiff(baseList[tuple.Base].Item2, compareList[tuple.Compare].Item2, bWriter, cWriter, results);
          bWriter.WriteEndElement();
          cWriter.WriteEndElement();
        }
        else if (baseList[tuple.Base].Item2.Elements().Any() || compareList[tuple.Compare].Item2.Elements().Any() || baseList[tuple.Base].Item2.Value != compareList[tuple.Compare].Item2.Value)
        {
          results.Add(new ListCompare(bWriter.CurrentLine + 1, cWriter.CurrentLine + 1) { IsDifferent = true });
          for (int i = results.Last().Base; i < bWriter.CurrentLine; i++)
            results.Add(new ListCompare(i, -1));
          for (int i = results.Last().Compare; i < cWriter.CurrentLine; i++)
            results.Add(new ListCompare(-1, i));
          bWriter.WriteElement(baseList[tuple.Base].Item2);
          cWriter.WriteElement(compareList[tuple.Compare].Item2);
        }
        else
        {
          results.Add(new ListCompare(bWriter.CurrentLine + 1, cWriter.CurrentLine + 1));
          bWriter.WriteElement(baseList[tuple.Base].Item2);
          cWriter.WriteElement(compareList[tuple.Compare].Item2);
        }
      }
    }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            try
            {
                // Read a PDF document from a stream or pass-in a memory buffer...
                FileStream istm = new FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read);
                using (PDFDoc doc = new PDFDoc(istm))
                    using (ElementWriter writer = new ElementWriter())
                        using (ElementReader reader = new ElementReader())
                        {
                            doc.InitSecurityHandler();

                            int num_pages = doc.GetPageCount();

                            Element element;

                            // Perform some document editing ...
                            // Here we simply copy all elements from one page to another.
                            for (int i = 1; i <= num_pages; ++i)
                            {
                                Page pg = doc.GetPage(2 * i - 1);

                                reader.Begin(pg);
                                Page new_page = doc.PageCreate(pg.GetMediaBox());
                                doc.PageInsert(doc.GetPageIterator(2 * i), new_page);

                                writer.Begin(new_page);
                                while ((element = reader.Next()) != null)                       // Read page contents
                                {
                                    writer.WriteElement(element);
                                }

                                writer.End();
                                reader.End();
                            }

                            doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveOptions.e_remove_unused);

                            // Save the document to a stream or a memory buffer...
                            using (FileStream ostm = new FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)) {
                                doc.Save(ostm, SDFDoc.SaveOptions.e_remove_unused);
                            }

                            // Read some data from the file stored in memory
                            reader.Begin(doc.GetPage(1));
                            while ((element = reader.Next()) != null)
                            {
                                if (element.GetType() == Element.Type.e_path)
                                {
                                    Console.Write("Path, ");
                                }
                            }
                            reader.End();

                            Console.WriteLine("");
                            Console.WriteLine("");
                            Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }