// 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);
                }
        }
Beispiel #2
0
        /// <summary>
        /// Stamp a JPEG image to a PDF document in a specific position
        /// </summary>
        /// <param name="doc">PDF Document to add the barcode</param>
        /// <param name="jpegBytes">The encoded JPEG byte array</param>
        /// <param name="h">Horizontal position</param>
        /// <param name="v">Vertical position</param>
        private void StampToPage(PDFDoc doc, byte[] jpegBytes, double h, double v)
        {
            // Stamping PDF file
            pdftron.PDF.Image barcodeImage = pdftron.PDF.Image.Create(doc.GetSDFDoc(), jpegBytes);

            Stamper barcodeStamp = new Stamper(StamperSizeType.e_absolute_size, 150, 150);

            //set position of the image to the center, left of PDF pages
            barcodeStamp.SetAlignment(StamperHorizontalAlignment.e_horizontal_left, StamperVerticalAlignment.e_vertical_bottom);
            barcodeStamp.SetAsAnnotation(true);

            double xPos = h - (150 / 2);
            double yPos = v - (150 / 2);

            barcodeStamp.SetPosition(xPos, yPos);
            barcodeStamp.SetFontColor(new ColorPt(0, 0, 0, 0));
            //barcodeStamp.SetRotation(180);
            barcodeStamp.SetAsBackground(false);
            // Stamp current viewing page
            barcodeStamp.StampImage(doc, barcodeImage, new PageSet(PDFViewCtrl.GetCurrentPage(), PDFViewCtrl.GetCurrentPage()));

            // Render current visible region
            PDFViewCtrl.Update();
        }
Beispiel #3
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            // Initialize PDFNet before calling any other PDFNet function.
            PDFNet.Initialize();

            string input_path     = "../../TestFiles/";
            string output_path    = "../../TestFiles/Output/";
            string input_filename = "US061222892-a.pdf";

            PDFDoc pdf_doc = new PDFDoc(input_path + input_filename);

            pdf_doc.InitSecurityHandler();

            SDFDoc cos_doc  = pdf_doc.GetSDFDoc();
            int    num_objs = cos_doc.XRefSize();

            for (int i = 1; i < num_objs; ++i)
            {
                Obj obj = cos_doc.GetObj(i);
                if (obj != null && !obj.IsFree() && obj.IsStream())
                {
                    // Process only images
                    DictIterator itr = obj.Find("Subtype");
                    if (!itr.HasNext() || itr.Value().GetName() != "Image")
                    {
                        continue;
                    }

                    pdftron.PDF.Image input_image = new pdftron.PDF.Image(obj);
                    pdftron.PDF.Image new_image   = null;

                    // Process only gray-scale images
                    if (input_image.GetComponentNum() != 1)
                    {
                        continue;
                    }

                    int bpc = input_image.GetBitsPerComponent();
                    if (bpc != 1)                     // Recompress 1 BPC images
                    {
                        continue;
                    }

                    // Skip images that are already compressed using JBIG2
                    itr = obj.Find("Filter");
                    if (itr.HasNext() && itr.Value().IsName() &&
                        itr.Value().GetName() == "JBIG2Decode")
                    {
                        continue;
                    }

                    FilterReader reader = new FilterReader(obj.GetDecodedStream());

                    ObjSet hint_set = new ObjSet();
                    Obj    hint     = hint_set.CreateArray();
                    hint.PushBackName("JBIG2");
                    hint.PushBackName("Lossless");
                    hint.PushBackName("Threshold");
                    hint.PushBackNumber(0.4);
                    hint.PushBackName("SharePages");
                    hint.PushBackNumber(10000);

                    new_image = pdftron.PDF.Image.Create(
                        cos_doc,
                        reader,
                        input_image.GetImageWidth(),
                        input_image.GetImageHeight(),
                        1,
                        ColorSpace.CreateDeviceGray(),
                        hint                          // A hint to image encoder to use JBIG2 compression
                        );

                    Obj new_img_obj = new_image.GetSDFObj();

                    // Copy any important entries from the image dictionary
                    itr = obj.Find("ImageMask");
                    if (itr.HasNext())
                    {
                        new_img_obj.Put("ImageMask", itr.Value());
                    }

                    itr = obj.Find("Mask");
                    if (itr.HasNext())
                    {
                        new_img_obj.Put("Mask", itr.Value());
                    }

                    cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum());
                }
            }

            pdf_doc.Save(output_path + "US061222892_JBIG2.pdf", SDFDoc.SaveOptions.e_remove_unused);
            pdf_doc.Close();
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Example 1:
            // Extract images by traversing the display list for
            // every page. With this approach it is possible to obtain
            // image positioning information and DPI.
            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                    using (ElementReader reader = new ElementReader())
                    {
                        doc.InitSecurityHandler();

                        PageIterator itr;
                        for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())
                        {
                            reader.Begin(itr.Current());
                            ImageExtract(doc, reader);
                            reader.End();
                        }

                        Console.WriteLine("Done.");
                    }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("----------------------------------------------------------------");

            // Example 2:
            // Extract images by scanning the low-level document.
            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                {
                    doc.InitSecurityHandler();
                    image_counter = 0;

                    SDFDoc cos_doc  = doc.GetSDFDoc();
                    int    num_objs = cos_doc.XRefSize();
                    for (int i = 1; i < num_objs; ++i)
                    {
                        Obj obj = cos_doc.GetObj(i);
                        if (obj != null && !obj.IsFree() && obj.IsStream())
                        {
                            // Process only images
                            DictIterator itr = obj.Find("Subtype");
                            if (!itr.HasNext() || itr.Value().GetName() != "Image")
                            {
                                continue;
                            }

                            itr = obj.Find("Type");
                            if (!itr.HasNext() || itr.Value().GetName() != "XObject")
                            {
                                continue;
                            }

                            pdftron.PDF.Image image = new pdftron.PDF.Image(obj);

                            Console.WriteLine("--> Image: {0}", ++image_counter);
                            Console.WriteLine("    Width: {0}", image.GetImageWidth());
                            Console.WriteLine("    Height: {0}", image.GetImageHeight());
                            Console.WriteLine("    BPC: {0}", image.GetBitsPerComponent());

                            string fname = output_path + "image_extract2_" + image_counter.ToString();
                            image.Export(fname);                              // or ExporAsPng() or ExporAsTiff() ...

                            // Convert PDF bitmap to GDI+ Bitmap...
                            //Bitmap bmp = image.GetBitmap();
                            //bmp.Save(fname, ImageFormat.Png);
                            //bmp.Dispose();

                            // Instead of converting PDF images to a Bitmap, you can also extract
                            // uncompressed/compressed image data directly using element.GetImageData()
                            // as illustrated in ElementReaderAdv sample project.
                        }
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #5
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/";

            //Example - Exporting images of each page in the document in parallel,
            //            and annotating the document in the main thread.
            try
            {
                // Open the PDF document.
                using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                {
                    // Lock the document, since we are going to annotate it in this thread.
                    doc.Lock();

                    // Initialize the security handler, in case the PDF is encrypted.
                    doc.InitSecurityHandler();

                    List <Task> tasks = new List <Task>();

                    // Iterate through each page in the document
                    for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())
                    {
                        //note that locking a second time does not cause a deadlock:
                        doc.Lock();

                        // You can acquire a read lock while holding a write lock:
                        doc.LockRead();
                        doc.UnlockRead();

                        // Choose an output path for this page
                        string page_output_path = output_path + "newsletter_" + itr.GetPageNumber() + ".png";

                        // Create an asynchronous task to draw the page
                        Page pg = itr.Current();
                        Task t  = new Task(() => DoDraw(doc, pg, page_output_path));
                        // Start the Task (although it won't be able to access the document, since we have a write lock)
                        t.Start();
                        // Add it to our list of Tasks so we can Wait() for it later.
                        tasks.Add(t);

                        Console.WriteLine("Adding stamp to PDFDoc, page " + itr.GetPageNumber());

                        // Create a stamp annotation (See AnnotationTest for more details)
                        pdftron.PDF.Annots.RubberStamp stamp = pdftron.PDF.Annots.RubberStamp.Create(doc.GetSDFDoc(), new Rect(30, 30, 300, 200));
                        stamp.SetIcon("Approved");
                        itr.Current().AnnotPushBack(stamp);

                        // Releasing the lock decrements our lock count,
                        // but the thread still holds a write lock on the document:
                        doc.Unlock();
                    }

                    // Now we release the write lock, and the
                    // PDFDraw tasks can begin execution
                    doc.Unlock();

                    // Wait for the PDFDraw tasks to complete.
                    foreach (Task t in tasks)
                    {
                        t.Wait();
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }