예제 #1
0
		//20130604 :: mellorasinxelas
		/// <summary>
		/// Draws the textblock
		/// </summary>
		/// <param name="pdfDraw"></param>
		/// <param name="data"></param>
		public override void Draw(PDFDraw.IPDFDraw pdfDraw, System.Collections.IDictionary data)
		{
			//            StringBuilder txt = new StringBuilder(Text);
			//            foreach (Variable act in VAR)
			//            {
//					string var = act.Name;
//
//					object dataV = data[var]; //null if not exists. Reduce HASH access.
//
//					//first of all if its formatable. This system supports null values.
//					if(act is FormatableVariable){
//						object formatV = ((FormatableVariable)act).GetFormatedValue(dataV);
//						txt.Replace(var, formatV != null? formatV.ToString() : null );
//					}
//					else if (dataV != null)
//					{    //original
//						txt.Replace(var, dataV.ToString() );
//					}
//					else if(PDFTemplate.UseOptionalTags && !act.Optional){
//						//only NOT optional vars with OptionalTags ON are replaced with empty value.
//						txt.Replace(var, "");
//					}
			//            }
			//change to super gettext.
			pdfDraw.DrawBlockString(GetText( data ), X, Width, FontAttributes, TextAttrs);
		}
예제 #2
0
 public PdfBookReader(PDFDoc book)
 {
     PDFNet.Initialize();
     pdftron.PDFNet.SetViewerCache(100 * 1024 * 1024, true);
     _book = book;
     m_draw = new PDFDraw();
 }
예제 #3
0
        /// <summary>
        /// A static method for rasterizing a given page to a file.
        /// </summary>
        static void DoDraw(PDFDoc doc, Page pg, string output_path)
        {
            //acquire a read lock, since we will be accessing the document.
            doc.LockRead();

            //Acquiring a write lock when holding a read lock is illegal,
            //and would cause an exception to be thrown:
            //doc.Lock();

            //draw the page
            using (PDFDraw draw = new PDFDraw())
            {
                draw.SetDPI(92);
                draw.Export(pg, output_path);
                Console.WriteLine("Rendered page: Result saved in {0}", output_path);
            }

            //release the read lock
            doc.UnlockRead();
        }
예제 #4
0
 public override void Draw(PDFDraw.IPDFDraw pdfDraw, System.Collections.Hashtable data)
 {
     pdfDraw.DrawHorizontalLine(this.x1, this.x2, RectangleAttrs);           
 }
예제 #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();

            try
            {
                // Optional: Set ICC color profiles to fine tune color conversion
                // for PDF 'device' color spaces. You can use your own ICC profiles.
                // Standard Adobe color profiles can be download from Adobes site:
                // http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
                //
                // Simply drop all *.icc files in PDFNet resource folder or you specify
                // the full pathname.
                //---
                // PDFNet.SetResourcesPath("../../../../../resources");
                // PDFNet.SetColorManagement();
                // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
                // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc");

                // Optional: Set predefined font mappings to override default font
                // substitution for documents with missing fonts. For example:
                //---
                // PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
                // PDFNet.AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
                //
                // If fonts are in PDFNet resource folder, it is not necessary to specify
                // the full path name. For example,
                //---
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
                // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");
            }
            catch (Exception)
            {
                Console.WriteLine("The specified color profile was not found.");
            }

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


            using (PDFDraw draw = new PDFDraw())
            {
                //--------------------------------------------------------------------------------
                // Example 1) Convert the first PDF page to PNG at 92 DPI.
                // A three step tutorial to convert PDF page to an image.
                try
                {
                    // A) Open the PDF document.
                    using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
                    {
                        // Initialize the security handler, in case the PDF is encrypted.
                        doc.InitSecurityHandler();

                        // B) The output resolution is set to 92 DPI.
                        draw.SetDPI(92);

                        // C) Rasterize the first page in the document and save the result as PNG.
                        Page pg = doc.GetPage(1);
                        draw.Export(pg, output_path + "tiger_92dpi.png");

                        Console.WriteLine("Example 1: tiger_92dpi.png");

                        // Export the same page as TIFF
                        draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF");
                    }
                }
                catch (PDFNetException e) {
                    Console.WriteLine(e.Message);
                }

                //--------------------------------------------------------------------------------
                // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
                ObjSet hint_set = new ObjSet();               // A collection of rendering 'hits'.
                Console.WriteLine("Example 2:");
                try
                {
                    using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
                    {
                        // Initialize the security handler, in case the PDF is encrypted.
                        doc.InitSecurityHandler();

                        draw.SetDPI(72);                         // Set the output resolution is to 72 DPI.

                        // Use optional encoder parameter to specify JPEG quality.
                        Obj encoder_param = hint_set.CreateDict();
                        encoder_param.PutNumber("Quality", 80);

                        // Traverse all pages in the document.
                        for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())
                        {
                            string output_filename = string.Format("newsletter{0:d}.jpg", itr.GetPageNumber());
                            Console.WriteLine("newsletter{0:d}.jpg", itr.GetPageNumber());
                            draw.Export(itr.Current(), output_path + output_filename, "JPEG", encoder_param);
                        }
                    }

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

                try                  // Examples 3-6
                {
                    // Common code for remaining samples.
                    using (PDFDoc tiger_doc = new PDFDoc(input_path + "tiger.pdf"))
                    {
                        // Initialize the security handler, in case the PDF is encrypted.
                        tiger_doc.InitSecurityHandler();
                        Page page = tiger_doc.GetPage(1);

                        //--------------------------------------------------------------------------------
                        // Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the
                        // page 90 degrees and save the result as RAW.
                        draw.SetDPI(100);                         // Set the output resolution is to 100 DPI.
                        draw.SetRotate(Page.Rotate.e_90);         // Rotate all pages 90 degrees clockwise.

                        BitmapInfo buf = draw.GetBitmap(page, PDFDraw.PixelFormat.e_rgb, false);

                        // Save the raw RGB data to disk.
                        string filename = "tiger_100dpi_rot90.raw";

                        System.IO.File.WriteAllBytes(output_path + filename, buf.Buffer);

                        Console.WriteLine("Example 3: tiger_100dpi_rot90.raw");
                        draw.SetRotate(Page.Rotate.e_0);                          // Disable image rotation for remaining samples.

                        //--------------------------------------------------------------------------------
                        // Example 4) Convert PDF page to a fixed image size. Also illustrates some
                        // other features in PDFDraw class such as rotation, image stretching, exporting
                        // to grayscale, or monochrome.

                        // Initialize render 'gray_hint' parameter, that is used to control the
                        // rendering process. In this case we tell the rasterizer to export the image as
                        // 1 Bit Per Component (BPC) image.
                        Obj mono_hint = hint_set.CreateDict();
                        mono_hint.PutNumber("BPC", 1);

                        // SetImageSize can be used instead of SetDPI() to adjust page  scaling
                        // dynamically so that given image fits into a buffer of given dimensions.
                        draw.SetImageSize(1000, 1000);                                  // Set the output image to be 1000 wide and 1000 pixels tall
                        draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint);
                        Console.WriteLine("Example 4: tiger_1000x1000.png");

                        draw.SetImageSize(200, 400);                                // Set the output image to be 200 wide and 300 pixels tall
                        draw.SetRotate(Page.Rotate.e_180);                          // Rotate all pages 90 degrees clockwise.

                        // 'gray_hint' tells the rasterizer to export the image as grayscale.
                        Obj gray_hint = hint_set.CreateDict();
                        gray_hint.PutName("ColorSpace", "Gray");

                        draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint);
                        Console.WriteLine("Example 4: tiger_200x400_rot180.png");

                        draw.SetImageSize(400, 200, false);                         // The third parameter sets 'preserve-aspect-ratio' to false.
                        draw.SetRotate(Page.Rotate.e_0);                            // Disable image rotation.
                        draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG");
                        Console.WriteLine("Example 4: tiger_400x200_stretch.jpg");

                        //--------------------------------------------------------------------------------
                        // Example 5) Zoom into a specific region of the page and rasterize the
                        // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
                        page.SetCropBox(new Rect(216, 522, 330, 600));                          // Set the page crop box.

                        // Select the crop region to be used for drawing.
                        draw.SetPageBox(Page.Box.e_crop);
                        draw.SetDPI(900);                          // Set the output image resolution to 900 DPI.
                        draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG");
                        Console.WriteLine("Example 5: tiger_zoom_900dpi.png");

                        // -------------------------------------------------------------------------------
                        // Example 6)
                        draw.SetImageSize(50, 50);         // Set the thumbnail to be 50x50 pixel image.
                        draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG");
                        Console.WriteLine("Example 6: tiger_zoom_50x50.png");
                    }
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine(e.Message);
                }

                Obj cmyk_hint = hint_set.CreateDict();
                cmyk_hint.PutName("ColorSpace", "CMYK");

                //--------------------------------------------------------------------------------
                // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
                // A three step tutorial to convert PDF page to an image.
                try
                {
                    // A) Open the PDF document.
                    using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
                    {
                        // Initialize the security handler, in case the PDF is encrypted.
                        doc.InitSecurityHandler();

                        // B) The output resolution is set to 92 DPI.
                        draw.SetDPI(92);

                        // C) Rasterize the first page in the document and save the result as TIFF.
                        Page pg = doc.GetPage(1);
                        draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
                        Console.WriteLine("Example 7: out1.tif");
                    }
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine(e.Message);
                }

                //--------------------------------------------------------------------------------
                // Example 8) Export raster content to PNG using different image smoothing settings.
                try
                {
                    // A) Open the PDF document.
                    using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
                    {
                        // Initialize the security handler, in case the PDF is encrypted.
                        doc.InitSecurityHandler();

                        // B) Get the page matrix
                        Page     pg  = doc.GetPage(1);
                        Page.Box box = Page.Box.e_crop;
                        Matrix2D mtx = pg.GetDefaultMatrix(true, box);
                        // We want to render a quadrant, so use half of width and height
                        double pg_w = pg.GetPageWidth(box) / 2;
                        double pg_h = pg.GetPageHeight(box) / 2;

                        // C) Scale matrix from PDF space to buffer space
                        double dpi             = 96.0;
                        double scale           = dpi / 72.0; // PDF space is 72 dpi
                        int    buf_w           = (int)(Math.Floor(scale * pg_w));
                        int    buf_h           = (int)(Math.Floor(scale * pg_h));
                        int    bytes_per_pixel = 4; // BGRA buffer
                        int    buf_size        = buf_w * buf_h * bytes_per_pixel;
                        mtx.Translate(0, -pg_h);    // translate by '-pg_h' since we want south-west quadrant
                        mtx = new Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;

                        // D) Rasterize page into memory buffer, according to our parameters
                        byte[]        buf;
                        PDFRasterizer rast = new PDFRasterizer();
                        buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);

                        // buf now contains raw BGRA bitmap.
                        Console.WriteLine("Example 8: Successfully rasterized into memory buffer.");
                    }
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine(e.Message);
                }
                //--------------------------------------------------------------------------------
                // Example 9) Export raster content to PNG using different image smoothing settings.
                try
                {
                    using (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf"))
                    {
                        text_doc.InitSecurityHandler();

                        draw.SetImageSmoothing(false, false);
                        string filename = "raster_text_no_smoothing.png";
                        draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
                        Console.WriteLine("Example 9 a): " + filename + ". Done.");

                        filename = "raster_text_smoothed.png";
                        draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
                        draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
                        Console.WriteLine("Example 9 b): " + filename + ". Done.");

                        filename = "raster_text_high_quality.png";
                        draw.SetImageSmoothing(true, true /*high quality area resampling*/);
                        draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
                        Console.WriteLine("Example 9 c): " + filename + ". Done.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                //--------------------------------------------------------------------------------
                // Example 10) Export separations directly, without conversion to an output colorspace
                try
                {
                    using (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf"))
                    {
                        separation_doc.InitSecurityHandler();
                        Obj separation_hint = hint_set.CreateDict();
                        separation_hint.PutName("ColorSpace", "Separation");
                        draw.SetDPI(96);
                        draw.SetImageSmoothing(true, true);
                        draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on);

                        string filename = "merged_separations.png";
                        draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG");
                        Console.WriteLine("Example 10 a): " + filename + ". Done.");

                        filename = "separation";
                        draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint);
                        Console.WriteLine("Example 10 b): " + filename + "_[ink].png. Done.");

                        filename = "separation_NChannel.tif";
                        draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint);
                        Console.WriteLine("Example 10 c): " + filename + ". Done.");
                    }
                }
                catch (PDFNetException e)
                {
                    Console.WriteLine(e.Message);
                }
            }              // using PDFDraw
        }
예제 #6
0
		//20130604 :: mellorasinxelas       
        
		/// <summary>
        /// Draws built-in image
        /// </summary>
        /// <param name="pdfDraw"></param>
        /// <param name="data"></param>
		public override void Draw(PDFDraw.IPDFDraw pdfDraw,IDictionary data)
        {
			//NOTE: Dont support format.           
        	StringBuilder src = new StringBuilder(Attributes[SrcAttributeConstant].Value);
            foreach (Variable act in VAR)
            {
                string var = act.Name;
            	if (data.Contains(var))
                {
                    src.Replace(var, data[var].ToString());
                }
                else if(PDFTemplate.UseOptionalTags && !act.Optional){
                	//only NOT optional vars with OptionalTags ON are replaced with empty value.
            		src.Replace(var, "");
                }   
            }                 

            
            //20150914 :: supports absolute X,Y.
            float absX = Moon.PDFDraw.Helper.GetFloatAttributeValue(AbsoluteXAttributeConstant, Attributes, -1);
			float absY = Moon.PDFDraw.Helper.GetFloatAttributeValue(AbsoluteYAttributeConstant, Attributes, -1);
			if (absX != -1 && absY != -1)
			{//new
				pdfDraw.DrawImage(absX, absY, /*src.ToString(),*/ Attributes);
			}
			else{//classic				
            	pdfDraw.DrawImage(X, src.ToString(), Attributes );
			}
			//---
        }
예제 #7
0
        void Execute(string[] args)
        {
            PDFNet.Initialize();

            // Optional: Set ICC color profiles to fine tune color conversion
            // for PDF 'device' color spaces. You can use your own ICC profiles.
            // Standard Adobe color profiles can be download from Adobes site:
            // http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
            //
            // Simply drop all *.icc files in PDFNet resource folder or you specify
            // the full pathname.
            try
            {
                // PDFNet.SetColorManagement();
                // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
                // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc");
            }
            catch (Exception)
            {
                Console.WriteLine("The specified color profile was not found.");
            }

            // Optional: Set predefined font mappings to override default font
            // substitution for documents with missing fonts. For example:
            //---
            // PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
            // PDFNet.AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
            //
            // If fonts are in PDFNet resource folder, it is not necessary to specify
            // the full path name. For example,
            //---
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
            // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");

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

            try
            {
                // Open the PDF document.
                Console.WriteLine("Opening the input file...");
                using (pdfdoc = new PDFDoc(input_path + "tiger.pdf"))
                {
                    pdfdoc.InitSecurityHandler();


                    //////////////////////////////////////////////////////////////////////////
                    // Example 1: use the PDF::Print::StartPrintJob interface
                    // This is silent (no progress dialog) and blocks until print job is at spooler
                    // The rasterized print job is compressed before sending to printer
                    Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob...");

                    // Setup printing options:
                    PrinterMode printerMode = new PrinterMode();
                    printerMode.SetAutoCenter(true);
                    printerMode.SetAutoRotate(true);
                    printerMode.SetCollation(true);
                    printerMode.SetCopyCount(1);
                    printerMode.SetDPI(300);                     // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
                    printerMode.SetDuplexing(PrinterMode.DuplexMode.e_Duplex_Auto);
                    printerMode.SetNUp(PrinterMode.NUp.e_NUp_1_1, PrinterMode.NUpPageOrder.e_PageOrder_LeftToRightThenTopToBottom);
                    printerMode.SetOrientation(PrinterMode.Orientation.e_Orientation_Portrait);
                    printerMode.SetOutputAnnot(PrinterMode.PrintContentTypes.e_PrintContent_DocumentAndAnnotations);

                    // If the XPS print path is being used, then the printer spooler file will
                    // ignore the grayscale option and be in full color
                    printerMode.SetOutputColor(PrinterMode.OutputColor.e_OutputColor_Grayscale);
                    printerMode.SetOutputPageBorder(false);
                    printerMode.SetOutputQuality(PrinterMode.OutputQuality.e_OutputQuality_Medium);
                    printerMode.SetPaperSize(new Rect(0, 0, 612, 792));
                    PageSet pagesToPrint = new PageSet(1, pdfdoc.GetPageCount(), PageSet.Filter.e_all);

                    // You can get the name of the default printer by using:
                    // PrinterSettings ps = new PrinterSettings();
                    // String printerName   ps.PrinterName();
                    // however Print.StartPrintJob can also determine this for you, just pass an empty printer name

                    // Print the document on the default printer, name the print job the name of the
                    // file, print to the printer not a file, and use printer options:
                    Print.StartPrintJob(pdfdoc, "", pdfdoc.GetFileName(), "", pagesToPrint, printerMode, null);


                    //////////////////////////////////////////////////////////////////////////
                    // Example 2: use the .Net PrintDocument class and PDFDraw rasterizer
                    // This will pop up a progress dialog

                    // Start printing from the first page
                    pageitr = pdfdoc.GetPageIterator();
                    pdfdraw = new PDFDraw();
                    pdfdraw.SetPrintMode(true);
                    pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn);

                    // Create a printer
                    PrintDocument printer = new PrintDocument();

                    // name the document to be printed
                    printer.DocumentName = pdfdoc.GetFileName();

                    // Set the PrintPage delegate which will be invoked to print each page
                    printer.PrintPage += new PrintPageEventHandler(PrintPage);

                    Console.WriteLine("Printing the input file using .NET PrintDocument and PDFDraw...");
                    printer.Print();                            // Start printing

                    pdfdraw.Dispose();                          // Free allocated resources (generally a good idea when printing many documents).
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
예제 #8
0
		/// <summary>
		/// Draws this textbox
		/// </summary>
		/// <param name="pdfDraw"></param>
		/// <param name="data"></param>
		public override void Draw(PDFDraw.IPDFDraw pdfDraw, System.Collections.IDictionary data)
		{
			pdfDraw.DrawString( GetText(data), X, Width, FontAttributes, Attributes);
		}
예제 #9
0
		/// <summary>
		/// Draws element
		/// </summary>
		/// <param name="pdfDraw"></param>
		/// <param name="data"></param>
		public override void Draw(PDFDraw.IPDFDraw pdfDraw, System.Collections.IDictionary data)
		{
			pdfDraw.DrawVerticalLine(this.x1, this.x2, lineAttrs);
		}
예제 #10
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);
            }
        }