Ejemplo n.º 1
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).
            // ...
        }
Ejemplo n.º 2
0
        // 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);
                }
        }
        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();
            }
        }
Ejemplo n.º 4
0
        // 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);
                }
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
0
        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
                }
        }
Ejemplo n.º 7
0
        // 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);
                }
        }
        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);
        }
Ejemplo n.º 10
0
        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
                }
        }
Ejemplo n.º 11
0
        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);
            }
        }
Ejemplo n.º 12
0
        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);
            }
        }
Ejemplo n.º 13
0
        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;
                }
            }
        }
Ejemplo n.º 14
0
        /// <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);
            }
        }
Ejemplo n.º 15
0
        /// <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);
            }
        }
Ejemplo n.º 16
0
        static void Create3DAnnotation(PDFDoc doc, Obj annots)
        {
            // ---------------------------------------------------------------------------------
            // Create a 3D annotation based on U3D content. PDF 1.6 introduces the capability
            // for collections of three-dimensional objects, such as those used by CAD software,
            // to be embedded in PDF files.
            Obj link_3D = doc.CreateIndirectDict();

            link_3D.PutName("Subtype", "3D");

            // Annotation location on the page
            Rect bbox = new Rect(25, 180, 585, 643);

            link_3D.PutRect("Rect", bbox.x1, bbox.y1, bbox.x2, bbox.y2);
            annots.PushBack(link_3D);

            // The 3DA entry is an activation dictionary (see Table 9.34 in the PDF Reference Manual)
            // that determines how the state of the annotation and its associated artwork can change.
            Obj activation_dict_3D = link_3D.PutDict("3DA");

            // Set the annotation so that it is activated as soon as the page containing the
            // annotation is opened. Other options are: PV (page view) and XA (explicit) activation.
            activation_dict_3D.PutName("A", "PO");

            // Embed U3D Streams (3D Model/Artwork).
            MappedFile   u3d_file   = new MappedFile(input_path + "dice.u3d");
            FilterReader u3d_reader = new FilterReader(u3d_file);

            Obj u3d_data_dict = doc.CreateIndirectStream(u3d_reader);

            u3d_data_dict.PutName("Subtype", "U3D");
            link_3D.Put("3DD", u3d_data_dict);

            // Set the initial view of the 3D artwork that should be used when the annotation is activated.
            Obj view3D_dict = link_3D.PutDict("3DV");

            view3D_dict.PutString("IN", "Unnamed");
            view3D_dict.PutString("XN", "Default");
            view3D_dict.PutName("MS", "M");
            view3D_dict.PutNumber("CO", 27.5);

            // A 12-element 3D transformation matrix that specifies a position and orientation
            // of the camera in world coordinates.
            Obj tr3d = view3D_dict.PutArray("C2W");

            tr3d.PushBackNumber(1); tr3d.PushBackNumber(0); tr3d.PushBackNumber(0);
            tr3d.PushBackNumber(0); tr3d.PushBackNumber(0); tr3d.PushBackNumber(-1);
            tr3d.PushBackNumber(0); tr3d.PushBackNumber(1); tr3d.PushBackNumber(0);
            tr3d.PushBackNumber(0); tr3d.PushBackNumber(-27.5); tr3d.PushBackNumber(0);

            // Create annotation appearance stream, a thumbnail which is used during printing or
            // in PDF processors that do not understand 3D data.
            Obj            ap_dict = link_3D.PutDict("AP");
            ElementBuilder builder = new ElementBuilder();
            ElementWriter  writer  = new ElementWriter();

            writer.Begin(doc);

            writer.WritePlacedElement(builder.CreateImage(
                                          Image.Create(doc, input_path + "dice.jpg"),
                                          0, 0, bbox.Width(), bbox.Height()));

            Obj normal_ap_stream = writer.End();

            normal_ap_stream.PutName("Subtype", "Form");
            normal_ap_stream.PutRect("BBox", 0, 0, bbox.Width(), bbox.Height());
            ap_dict.Put("N", normal_ap_stream);
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            try
            {
                using (PDFDoc doc = new PDFDoc())
                    using (ElementBuilder builder = new ElementBuilder())          // ElementBuilder is used to build new Element objects
                        using (ElementWriter writer = new ElementWriter())         // ElementWriter is used to write Elements to the page
                        {
                            // Create three layers...
                            Group image_layer  = CreateLayer(doc, "Image Layer");
                            Group text_layer   = CreateLayer(doc, "Text Layer");
                            Group vector_layer = CreateLayer(doc, "Vector Layer");

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

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

                            // Add new content to the page and associate it with one of the layers.
                            Element element = builder.CreateForm(CreateGroup1(doc, image_layer.GetSDFObj()));
                            writer.WriteElement(element);

                            element = builder.CreateForm(CreateGroup2(doc, vector_layer.GetSDFObj()));
                            writer.WriteElement(element);

                            // Add the text layer to the page...
                            bool enableOCMD = false;             // set to 'true' to enable 'ocmd' example.
                            if (enableOCMD)
                            {
                                // A bit more advanced example of how to create an OCMD text layer that
                                // is visible only if text, image and path layers are all 'ON'.
                                // An example of how to set 'Visibility Policy' in OCMD.
                                Obj ocgs = doc.CreateIndirectArray();
                                ocgs.PushBack(image_layer.GetSDFObj());
                                ocgs.PushBack(vector_layer.GetSDFObj());
                                ocgs.PushBack(text_layer.GetSDFObj());
                                OCMD text_ocmd = OCMD.Create(doc, ocgs, OCMD.VisibilityPolicyType.e_AllOn);
                                element = builder.CreateForm(CreateGroup3(doc, text_ocmd.GetSDFObj()));
                            }
                            else
                            {
                                element = builder.CreateForm(CreateGroup3(doc, text_layer.GetSDFObj()));
                            }
                            writer.WriteElement(element);

                            // Add some content to the page that does not belong to any layer...
                            // In this case this is a rectangle representing the page border.
                            element = builder.CreateRect(0, 0, page.GetPageWidth(), page.GetPageHeight());
                            element.SetPathFill(false);
                            element.SetPathStroke(true);
                            element.GetGState().SetLineWidth(40);
                            writer.WriteElement(element);

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

                            // Set the default viewing preference to display 'Layer' tab.
                            PDFDocViewPrefs prefs = doc.GetViewPrefs();
                            prefs.SetPageMode(PDFDocViewPrefs.PageMode.e_UseOC);

                            doc.Save(output_path + "pdf_layers.pdf", SDFDoc.SaveOptions.e_linearized);
                            Console.WriteLine("Done.");
                        }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // The following is a code snippet shows how to selectively render
            // and export PDF layers.
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "pdf_layers.pdf"))
                {
                    doc.InitSecurityHandler();

                    if (!doc.HasOC())
                    {
                        Console.WriteLine("The document does not contain 'Optional Content'");
                    }
                    else
                    {
                        Config  init_cfg = doc.GetOCGConfig();
                        Context ctx      = new Context(init_cfg);

                        using (PDFDraw pdfdraw = new PDFDraw())
                        {
                            pdfdraw.SetImageSize(1000, 1000);
                            pdfdraw.SetOCGContext(ctx);                             // Render the page using the given OCG context.

                            Page page = doc.GetPage(1);                             // Get the first page in the document.
                            pdfdraw.Export(page, output_path + "pdf_layers_default.png");

                            // Disable drawing of content that is not optional (i.e. is not part of any layer).
                            ctx.SetNonOCDrawing(false);

                            // Now render each layer in the input document to a separate image.
                            Obj ocgs = doc.GetOCGs();                             // Get the array of all OCGs in the document.
                            if (ocgs != null)
                            {
                                int i, sz = ocgs.Size();
                                for (i = 0; i < sz; ++i)
                                {
                                    Group ocg = new Group(ocgs.GetAt(i));
                                    ctx.ResetStates(false);
                                    ctx.SetState(ocg, true);
                                    string fname = "pdf_layers_" + ocg.GetName() + ".png";
                                    Console.WriteLine(fname);
                                    pdfdraw.Export(page, fname);
                                }
                            }

                            // Now draw content that is not part of any layer...
                            ctx.SetNonOCDrawing(true);
                            ctx.SetOCDrawMode(Context.OCDrawMode.e_NoOC);
                            pdfdraw.Export(page, output_path + "pdf_layers_non_oc.png");

                            Console.WriteLine("Done.");
                        }
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 18
0
        private static void CreateTestAnnots(PDFDoc doc)
        {
            ElementWriter  ew = new ElementWriter();
            ElementBuilder eb = new ElementBuilder();
            Element        element;

            Page first_page = doc.PageCreate(new Rect(0, 0, 600, 600));

            doc.PagePushBack(first_page);
            ew.Begin(first_page, ElementWriter.WriteMode.e_overlay, false); // begin writing to this page
            ew.End();                                                       // save changes to the current page

            //
            // Test of a free text annotation.
            //
            {
                FreeText txtannot = FreeText.Create(doc, new Rect(10, 400, 160, 570));
                txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." +
                                     "\n\nAha!\n\nAnd there was much rejoicing!");
                txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20));
                txtannot.SetQuaddingFormat(0);
                first_page.AnnotPushBack(txtannot);
                txtannot.RefreshAppearance();
            }
            {
                FreeText txtannot = FreeText.Create(doc, new Rect(100, 100, 350, 500));
                txtannot.SetContentRect(new Rect(200, 200, 350, 500));
                txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." +
                                     "\n\nAha!\n\nAnd there was much rejoicing!");
                txtannot.SetCalloutLinePoints(new Point(200, 300), new Point(150, 290), new Point(110, 110));
                txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20));
                txtannot.SetEndingStyle(Line.EndingStyle.e_ClosedArrow);
                txtannot.SetColor(new ColorPt(0, 1, 0));
                txtannot.SetQuaddingFormat(1);
                first_page.AnnotPushBack(txtannot);
                txtannot.RefreshAppearance();
            }
            {
                FreeText txtannot = FreeText.Create(doc, new Rect(400, 10, 550, 400));
                txtannot.SetContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." +
                                     "\n\nAha!\n\nAnd there was much rejoicing!");
                txtannot.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 1, 10, 20));
                txtannot.SetColor(new ColorPt(0, 0, 1));
                txtannot.SetOpacity(0.2);
                txtannot.SetQuaddingFormat(2);
                first_page.AnnotPushBack(txtannot);
                txtannot.RefreshAppearance();
            }

            Page page = doc.PageCreate(new Rect(0, 0, 600, 600));

            doc.PagePushBack(page);
            ew.Begin(page, ElementWriter.WriteMode.e_overlay, false); // begin writing to this page
            eb.Reset();                                               // Reset the GState to default
            ew.End();                                                 // save changes to the current page

            {
                //Create a Line annotation...
                Line line = Line.Create(doc, new Rect(250, 250, 400, 400));
                line.SetStartPoint(new Point(350, 270));
                line.SetEndPoint(new Point(260, 370));
                line.SetStartStyle(Line.EndingStyle.e_Square);
                line.SetEndStyle(Line.EndingStyle.e_Circle);
                line.SetColor(new ColorPt(.3, .5, 0), 3);
                line.SetContents("Dashed Captioned");
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                double[] dash = new double[2];
                dash[0] = 2;
                dash[1] = 2.0;
                line.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 2, 0, 0, dash));
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(347, 377, 600, 600));
                line.SetStartPoint(new Point(385, 410));
                line.SetEndPoint(new Point(540, 555));
                line.SetStartStyle(Line.EndingStyle.e_Circle);
                line.SetEndStyle(Line.EndingStyle.e_OpenArrow);
                line.SetColor(new ColorPt(1, 0, 0), 3);
                line.SetInteriorColor(new ColorPt(0, 1, 0), 3);
                line.SetContents("Inline Caption");
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Inline);
                line.SetLeaderLineExtensionLength(-4);
                line.SetLeaderLineLength(-12);
                line.SetLeaderLineOffset(2);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(10, 400, 200, 600));
                line.SetStartPoint(new Point(25, 426));
                line.SetEndPoint(new Point(180, 555));
                line.SetStartStyle(Line.EndingStyle.e_Circle);
                line.SetEndStyle(Line.EndingStyle.e_Square);
                line.SetColor(new ColorPt(0, 0, 1), 3);
                line.SetInteriorColor(new ColorPt(1, 0, 0), 3);
                line.SetContents("Offset Caption");
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.SetTextHOffset(-60);
                line.SetTextVOffset(10);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(200, 10, 400, 70));
                line.SetStartPoint(new Point(220, 25));
                line.SetEndPoint(new Point(370, 60));
                line.SetStartStyle(Line.EndingStyle.e_Butt);
                line.SetEndStyle(Line.EndingStyle.e_OpenArrow);
                line.SetColor(new ColorPt(0, 0, 1), 3);
                line.SetContents("Regular Caption");
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(200, 70, 400, 130));
                line.SetStartPoint(new Point(220, 111));
                line.SetEndPoint(new Point(370, 78));
                line.SetStartStyle(Line.EndingStyle.e_Circle);
                line.SetEndStyle(Line.EndingStyle.e_Diamond);
                line.SetContents("Circle to Diamond");
                line.SetColor(new ColorPt(0, 0, 1), 3);
                line.SetInteriorColor(new ColorPt(0, 1, 0), 3);
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(10, 100, 160, 200));
                line.SetStartPoint(new Point(15, 110));
                line.SetEndPoint(new Point(150, 190));
                line.SetStartStyle(Line.EndingStyle.e_Slash);
                line.SetEndStyle(Line.EndingStyle.e_ClosedArrow);
                line.SetContents("Slash to CArrow");
                line.SetColor(new ColorPt(1, 0, 0), 3);
                line.SetInteriorColor(new ColorPt(0, 1, 1), 3);
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(270, 270, 570, 433));
                line.SetStartPoint(new Point(300, 400));
                line.SetEndPoint(new Point(550, 300));
                line.SetStartStyle(Line.EndingStyle.e_RClosedArrow);
                line.SetEndStyle(Line.EndingStyle.e_ROpenArrow);
                line.SetContents("ROpen & RClosed arrows");
                line.SetColor(new ColorPt(0, 0, 1), 3);
                line.SetInteriorColor(new ColorPt(0, 1, 0), 3);
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(195, 395, 205, 505));
                line.SetStartPoint(new Point(200, 400));
                line.SetEndPoint(new Point(200, 500));
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(55, 299, 150, 301));
                line.SetStartPoint(new Point(55, 300));
                line.SetEndPoint(new Point(155, 300));
                line.SetStartStyle(Line.EndingStyle.e_Circle);
                line.SetEndStyle(Line.EndingStyle.e_Circle);
                line.SetContents("Caption that's longer than its line.");
                line.SetColor(new ColorPt(1, 0, 1), 3);
                line.SetInteriorColor(new ColorPt(0, 1, 0), 3);
                line.SetShowCaption(true);
                line.SetCaptionPosition(Line.CapPos.e_Top);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }
            {
                Line line = Line.Create(doc, new Rect(300, 200, 390, 234));
                line.SetStartPoint(new Point(310, 210));
                line.SetEndPoint(new Point(380, 220));
                line.SetColor(new ColorPt(0, 0, 0), 3);
                line.RefreshAppearance();
                page.AnnotPushBack(line);
            }

            Page page3 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page3); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page3);
            {
                Circle circle = Circle.Create(doc, new Rect(300, 300, 390, 350));
                circle.SetColor(new ColorPt(0, 0, 0), 3);
                circle.RefreshAppearance();
                page3.AnnotPushBack(circle);
            }
            {
                Circle circle = Circle.Create(doc, new Rect(100, 100, 200, 200));
                circle.SetColor(new ColorPt(0, 1, 0), 3);
                circle.SetInteriorColor(new ColorPt(0, 0, 1), 3);
                double[] dash = new double[2];
                dash[0] = 2; dash[1] = 4;
                circle.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 3, 0, 0, dash));
                circle.SetPadding(new Rect(2, 2, 2, 2));
                circle.RefreshAppearance();
                page3.AnnotPushBack(circle);
            }
            {
                Square sq = Square.Create(doc, new Rect(10, 200, 80, 300));
                sq.SetColor(new ColorPt(0, 0, 0), 3);
                sq.RefreshAppearance();
                page3.AnnotPushBack(sq);
            }
            {
                Square sq = Square.Create(doc, new Rect(500, 200, 580, 300));
                sq.SetColor(new ColorPt(1, 0, 0), 3);
                sq.SetInteriorColor(new ColorPt(0, 1, 1), 3);
                double[] dash = new double[2];
                dash[0] = 4; dash[1] = 2;
                sq.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_dashed, 6, 0, 0, dash));
                sq.SetPadding(new Rect(4, 4, 4, 4));
                sq.RefreshAppearance();
                page3.AnnotPushBack(sq);
            }
            {
                Polygon poly = Polygon.Create(doc, new Rect(5, 500, 125, 590));
                poly.SetColor(new ColorPt(1, 0, 0), 3);
                poly.SetInteriorColor(new ColorPt(1, 1, 0), 3);
                poly.SetVertex(0, new Point(12, 510));
                poly.SetVertex(1, new Point(100, 510));
                poly.SetVertex(2, new Point(100, 555));
                poly.SetVertex(3, new Point(35, 544));
                poly.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 4, 0, 0));
                poly.SetPadding(new Rect(4, 4, 4, 4));
                poly.RefreshAppearance();
                page3.AnnotPushBack(poly);
            }
            {
                PolyLine poly = PolyLine.Create(doc, new Rect(400, 10, 500, 90));
                poly.SetColor(new ColorPt(1, 0, 0), 3);
                poly.SetInteriorColor(new ColorPt(0, 1, 0), 3);
                poly.SetVertex(0, new Point(405, 20));
                poly.SetVertex(1, new Point(440, 40));
                poly.SetVertex(2, new Point(410, 60));
                poly.SetVertex(3, new Point(470, 80));
                poly.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 2, 0, 0));
                poly.SetPadding(new Rect(4, 4, 4, 4));
                poly.SetStartStyle(Line.EndingStyle.e_RClosedArrow);
                poly.SetEndStyle(Line.EndingStyle.e_ClosedArrow);
                poly.RefreshAppearance();
                page3.AnnotPushBack(poly);
            }
            {
                Link lk = Link.Create(doc, new Rect(5, 5, 55, 24));
                //lk.SetColor( ColorPt(0,1,0), 3 );
                lk.RefreshAppearance();
                page3.AnnotPushBack(lk);
            }


            Page page4 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page4); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page4);

            {
                ew.Begin(page4);
                Font font = Font.Create(doc, Font.StandardType1Font.e_helvetica);
                element = eb.CreateTextBegin(font, 16);
                element.SetPathFill(true);
                ew.WriteElement(element);
                element = eb.CreateTextRun("Some random text on the page", font, 16);
                element.SetTextMatrix(1, 0, 0, 1, 100, 500);
                ew.WriteElement(element);
                ew.WriteElement(eb.CreateTextEnd());
                ew.End();
            }
            {
                Highlight hl = Highlight.Create(doc, new Rect(100, 490, 150, 515));
                hl.SetColor(new ColorPt(0, 1, 0), 3);
                hl.RefreshAppearance();
                page4.AnnotPushBack(hl);
            }
            {
                Squiggly sq = Squiggly.Create(doc, new Rect(100, 450, 250, 600));
                //sq.SetColor( ColorPt(1,0,0), 3 );
                sq.SetQuadPoint(0, new QuadPoint(new Point(122, 455), new Point(240, 545), new Point(230, 595), new Point(101, 500)));
                sq.RefreshAppearance();
                page4.AnnotPushBack(sq);
            }
            {
                Caret cr = Caret.Create(doc, new Rect(100, 40, 129, 69));
                cr.SetColor(new ColorPt(0, 0, 1), 3);
                cr.SetSymbol("P");
                cr.RefreshAppearance();
                page4.AnnotPushBack(cr);
            }


            Page page5 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page5); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page5);
            Page page6 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page6); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page6);

            {
                Text txt = Text.Create(doc, new Rect(10, 20, 30, 40));
                txt.SetIcon("UserIcon");
                txt.SetContents("User defined icon, unrecognized by appearance generator");
                txt.SetColor(new ColorPt(0, 1, 0));
                txt.RefreshAppearance();
                page6.AnnotPushBack(txt);
            }
            {
                Ink ink = Ink.Create(doc, new Rect(100, 400, 200, 550));
                ink.SetColor(new ColorPt(0, 0, 1));
                ink.SetPoint(1, 3, new Point(220, 505));
                ink.SetPoint(1, 0, new Point(100, 490));
                ink.SetPoint(0, 1, new Point(120, 410));
                ink.SetPoint(0, 0, new Point(100, 400));
                ink.SetPoint(1, 2, new Point(180, 490));
                ink.SetPoint(1, 1, new Point(140, 440));
                ink.SetBorderStyle(new Annot.BorderStyle(Annot.BorderStyle.Style.e_solid, 3, 0, 0));
                ink.RefreshAppearance();
                page6.AnnotPushBack(ink);
            }


            Page page7 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page7); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page7);

            {
                Sound snd = Sound.Create(doc, new Rect(100, 500, 120, 520));
                snd.SetColor(new ColorPt(1, 1, 0));
                snd.SetIcon(Sound.Icon.e_Speaker);
                snd.RefreshAppearance();
                page7.AnnotPushBack(snd);
            }
            {
                Sound snd = Sound.Create(doc, new Rect(200, 500, 220, 520));
                snd.SetColor(new ColorPt(1, 1, 0));
                snd.SetIcon(Sound.Icon.e_Mic);
                snd.RefreshAppearance();
                page7.AnnotPushBack(snd);
            }

            Page page8 = doc.PageCreate(new Rect(0, 0, 600, 600));

            ew.Begin(page8); // begin writing to the page
            ew.End();        // save changes to the current page
            doc.PagePushBack(page8);

            for (int ipage = 0; ipage < 2; ++ipage)
            {
                double px = 5, py = 520;
                for (RubberStamp.Icon istamp = RubberStamp.Icon.e_Approved;
                     istamp <= RubberStamp.Icon.e_Draft;
                     istamp = (RubberStamp.Icon)((int)(istamp) + 1))
                {
                    RubberStamp stmp = RubberStamp.Create(doc, new Rect(1, 1, 100, 100));
                    stmp.SetIcon(istamp);
                    stmp.SetContents(stmp.GetIconName());
                    stmp.SetRect(new Rect(px, py, px + 100, py + 25));
                    py -= 100;
                    if (py < 0)
                    {
                        py  = 520;
                        px += 200;
                    }
                    if (ipage == 0)
                    {
                        //page7.AnnotPushBack( st );
                        ;
                    }
                    else
                    {
                        page8.AnnotPushBack(stmp);
                        stmp.RefreshAppearance();
                    }
                }
            }
            RubberStamp st = RubberStamp.Create(doc, new Rect(400, 5, 550, 45));

            st.SetIcon("UserStamp");
            st.SetContents("User defined stamp");
            page8.AnnotPushBack(st);
            st.RefreshAppearance();
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
        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);
            }
        }
Ejemplo n.º 21
0
        // Note: This demo assumes that 'arialuni.ttf' is present in '/Samples/TestFiles'
        // directory. Arial Unicode MS is about 24MB in size and it comes together with Windows and
        // MS Office.
        //
        // For more information about Arial Unicode MS, please consult the following Microsoft Knowledge
        // Base Article: WD2002: General Information About the Arial Unicode MS Font
        //  http://support.microsoft.com/support/kb/articles/q287/2/47.asp
        //
        // For more information consult:
        //    http://office.microsoft.com/search/results.aspx?Scope=DC&Query=font&CTT=6&Origin=EC010331121033
        //    http://www.microsoft.com/downloads/details.aspx?FamilyID=1F0303AE-F055-41DA-A086-A65F22CB5593
        //
        // In case you don't have access to Arial Unicode MS you can use cyberbit.ttf
        // (ftp://ftp.netscape.com/pub/communicator/extras/fonts/windows/) instead.
        //
        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())
                    {
                        using (ElementWriter writer = new ElementWriter())
                        {
                            // Start a new page ------------------------------------
                            Page page = doc.PageCreate(new Rect(0, 0, 612, 794));

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

                            Font fnt;
                            try
                            {
                                // Full font embedding
                                fnt = Font.Create(doc, "Arial", "");

                                // To embed the font file directly use:
                                // fnt = Font.CreateCIDTrueTypeFont(doc, input_path + "arialuni.ttf", true, true);

                                // Example of font substitution
                                // fnt = Font.CreateCIDTrueTypeFont(doc, input_path + "arialuni.ttf", false);
                            }
                            catch (PDFNetException e)
                            {
                                Console.WriteLine(e.Message);
                                Console.WriteLine();

                                Console.WriteLine("'arialuni.ttf' font file was not found in 'Samples/TestFiles' directory.");
                                return;
                            }

                            Element element = eb.CreateTextBegin(fnt, 1);
                            element.SetTextMatrix(10, 0, 0, 10, 50, 600);
                            element.GetGState().SetLeading(2);                                           // Set the spacing between lines
                            writer.WriteElement(element);

                            // Hello World!!!
                            string hello = "Hello World!";
                            writer.WriteElement(eb.CreateUnicodeTextRun(hello));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Latin
                            char[] latin =
                            {
                                'a',      'A',      'b',      'B',      'c',      'C',      'd', 'D', '\x45', '\x0046', '\x00C0',
                                '\x00C1', '\x00C2', '\x0143', '\x0144', '\x0145', '\x0152', '1', '2'                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(latin)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Greek
                            char[] greek =
                            {
                                (char)0x039E, (char)0x039F, (char)0x03A0, (char)0x03A1, (char)0x03A3,
                                (char)0x03A6, (char)0x03A8, (char)0x03A9                                  // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(greek)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Cyrillic
                            char[] cyrillic =
                            {
                                (char)0x0409, (char)0x040A, (char)0x040B, (char)0x040C, (char)0x040E, (char)0x040F, (char)0x0410, (char)0x0411,
                                (char)0x0412, (char)0x0413, (char)0x0414, (char)0x0415, (char)0x0416, (char)0x0417, (char)0x0418, (char)0x0419                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(cyrillic)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Hebrew
                            char[] hebrew =
                            {
                                (char)0x05D0, (char)0x05D1, (char)0x05D3, (char)0x05D3, (char)0x05D4, (char)0x05D5, (char)0x05D6, (char)0x05D7, (char)0x05D8,
                                (char)0x05D9, (char)0x05DA, (char)0x05DB, (char)0x05DC, (char)0x05DD, (char)0x05DE, (char)0x05DF, (char)0x05E0, (char)0x05E1                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(hebrew)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Arabic
                            char[] arabic =
                            {
                                (char)0x0624, (char)0x0625, (char)0x0626, (char)0x0627, (char)0x0628, (char)0x0629, (char)0x062A, (char)0x062B, (char)0x062C,
                                (char)0x062D, (char)0x062E, (char)0x062F, (char)0x0630, (char)0x0631, (char)0x0632, (char)0x0633, (char)0x0634, (char)0x0635                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(arabic)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Thai
                            char[] thai =
                            {
                                (char)0x0E01, (char)0x0E02, (char)0x0E03, (char)0x0E04, (char)0x0E05, (char)0x0E06, (char)0x0E07, (char)0x0E08, (char)0x0E09,
                                (char)0x0E0A, (char)0x0E0B, (char)0x0E0C, (char)0x0E0D, (char)0x0E0E, (char)0x0E0F, (char)0x0E10, (char)0x0E11, (char)0x0E12                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(thai)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // Hiragana - Japanese
                            char[] hiragana =
                            {
                                (char)0x3041, (char)0x3042, (char)0x3043, (char)0x3044, (char)0x3045, (char)0x3046, (char)0x3047, (char)0x3048, (char)0x3049,
                                (char)0x304A, (char)0x304B, (char)0x304C, (char)0x304D, (char)0x304E, (char)0x304F, (char)0x3051, (char)0x3051, (char)0x3052                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(hiragana)));
                            writer.WriteElement(eb.CreateTextNewLine());

                            // CJK Unified Ideographs
                            char[] cjk_uni =
                            {
                                (char)0x5841, (char)0x5842, (char)0x5843, (char)0x5844, (char)0x5845, (char)0x5846, (char)0x5847, (char)0x5848, (char)0x5849,
                                (char)0x584A, (char)0x584B, (char)0x584C, (char)0x584D, (char)0x584E, (char)0x584F, (char)0x5850, (char)0x5851, (char)0x5852                                 // etc.
                            };
                            writer.WriteElement(eb.CreateUnicodeTextRun(new string(cjk_uni)));
                            writer.WriteElement(eb.CreateTextNewLine());

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

                            writer.End();                              // save changes to the current page
                            doc.PagePushBack(page);
                            doc.Save(output_path + "unicodewrite.pdf", SDFDoc.SaveOptions.e_remove_unused | SDFDoc.SaveOptions.e_hex_strings);
                            Console.WriteLine("Done. Result saved in unicodewrite.pdf...");
                        }
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }