working on it ...

Filters

Explore Public Snippets

Sort by

Found 18k snippets matching: library

    public by sukhjinderkahlon modified Mar 9, 2016  325958  6  5  0

    How to Work with Excel Files Using Apache POI

    This code will work as a utility to read and write excel files using Apache POI Library. 3.13
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelUtils {
    
    	private static HSSFSheet ExcelWSheet;
    	private static HSSFWorkbook ExcelWBook;
    	private static HSSFCell Cell;
    
    	private static HSSFRow Row;
    	
    	private static String filePath;
    	public static void setExcelFile(String Path,String SheetName) throws Exception {
    
    			try {
    
       			// Open the Excel file
    				filePath=Path;
    
    			FileInputStream ExcelFile = new FileInputStream(Path);
    
    			// Access the required test data sheet
    
    			ExcelWBook = new HSSFWorkbook(ExcelFile);
    
    			ExcelWSheet = ExcelWBook.getSheet(SheetName);
    			
    
    			} catch (Exception e){
    
    				throw (e);
    
    			}
    
    	}
    
    	//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    
        public static String getCellData(int RowNum, int ColNum) throws Exception{
    
    			try{
    
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    
      			String CellData = Cell.getStringCellValue();
    
      			return CellData;
    
      			}catch (Exception e){
    
    				return"";
    
      			}
    
        }
    
    
        
      //This method is to write in the Excel cell, Row num and Col num are the parameters
    
    	public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception	{
    
    			try{
    
      			Row  = ExcelWSheet.getRow(RowNum);
    
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    
    			if (Cell == null) {
    
    				Cell = Row.createCell(ColNum);
    
    				Cell.setCellValue(Result);
    
    				} else {
    
    					Cell.setCellValue(Result);
    
    				}
    
      // Constant variables Test Data path and Test Data file name
    
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    
      				ExcelWBook.write(fileOut);
    
      				fileOut.flush();
    
    					fileOut.close();
    
    				}catch(Exception e){
    
    					throw (e);
    
    			}
    
    		}
    
    	
    }
              

    public by David Grayson modified Aug 20, 2015  198268  1  3  0

    Woe unto any user that doesn't know that "pow" is a standard library function in C. The C standard allows this inconsistent behavior, sadly (Section 7.1.3 of N1124). I think C++ is better, at least based on how GCC behaves.

    Woe unto any user that doesn't know that "pow" is a standard library function in C. The C standard allows this inconsistent behavior, sadly (Section 7.1.3 of N1124). I think C++ is better, at least based on how GCC behaves.: pow_wtf.c
    #include <stdio.h>
    
    double pow(double x, double y)
    {
        return x + y;
    }
    
    int main()
    {
        volatile int y = 1;
        printf("%f\n", pow(10, y));  // prints 11.000000
        printf("%f\n", pow(10, 1));  // prints 10.000000
        return 0;
    }
    
    

    public by enlacee modified Jun 19, 2015  189137  0  3  0

    Library for page blogger JS

    Library for page blogger JS: blogger.theme.function.01.js
    /**
    * Library for page blogger JS
    */
    
    function bp_thumbnail_resize(image_url, post_title) {
        var image_width = 317;
        var image_height = 210;
        image_tag = '<img width="' + image_width + '" height="' + image_height + '" src="' + image_url.replace('/s72-c/', '/w' + image_width + '-h' + image_height + '-c/') + '" alt="' + post_title.replace(/"/g, "") + '" title="' + post_title.replace(/"/g, "") + '"/>';
        if (post_title != "")
            return image_tag;
        else
            return""
    }
    
    
    

    public by cghersi modified Jan 29, 2016  101511  294  12  10

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by DanielOgbuagu modified Jun 28, 2015  201454  1  5  0

    Adding a *.jar file (originating from java-wrapped C++ code) to an SBT project classpath

    I thought using unmanaged dependencies in SBT projects was simply dropping a jar file into the lib directory, until I bought an SDK for a biometric device. Both the C++ and the Java packages were provided. I opted for the Java package, copying the provided jar file and the JNI (*.so) files into the appropriate locations and configuring the ja
    /**
     * In my <code>build.sbt</code> file, I appended a blank line and then the following:
     */
    
    libraryDependencies += "groupID" % "artifactId" % "revision" from "file:///home/Danogbuagu/Projects/biometric-lib/filename.jar"
    
    // where,
    // groupID for example is like: com.zigzagcompany 
    // artifactId for example is like: zigzag
    // revision for example is like: 1.3.4
    // Remember the line befor the code and that after.

    public by micurs modified Mar 12, 2014  37627  391  10  8

    Using crypto-js in node.js with Typescript

    You can easily install the crypto-js library in node by using the command (on Mac): npm install crypto-js After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/cryptojs To make it work, however you need to add the following to the cryptojs.d.ts:
    // add this at the end of crypto.d.ts
      declare module "crypto-js" {
        export = CryptoJS;
      }
    
    // Then you can use the module in typescript
    
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/cryptojs.d.ts'/>
    
    import crypto = require("crypto-js");  
    
    function writeln( msg: string ) {
      process.stdout.write( msg +'\n');
    }
    
    var message : string = "Hello Encrypted World!";
    var cmessage : string = crypto.HmacSHA1( message , "1234").toString();
    writeln( message );
    writeln( cmessage );
    

    public by cghersi modified Mar 18, 2014  2902  1  7  0

    Consume a web service using Apache CXF client library

    Apache CXF may also be used to consume a web service. Obviously, the match of client and server both with CXF make the development very simple, as the same IMyAPI interface may be used as a contract between server and client.
    import java.net.MalformedURLException;
    import java.net.URL;
    
    
    public class CxfClientImpl {
    
        private static final QName SERVICE_NAME = new QName("http://com.snip2code.api", "MyAPIService");
        private static final QName PORT_NAME_DB = new QName("http://com.snip2code.api", "apiName");
    	
    	private IMyAPI portAPI;
    
    	public CxfClientImpl() {
    		//initialize web service utilities:
    		URL wsdlURL = null;
    		String location = "http://192.168.1.5:1572/MyAPIService";
    		try {
    			wsdlURL = new URL(location);
    		} catch (MalformedURLException e) {
    			log.error("Malformed Url:" + location + ", due to:" + e.getMessage());
    			return;
    		}
            Service service = Service.create(SERVICE_NAME);
            service.addPort(SERVICE_NAME, SOAPBinding.SOAP11HTTP_BINDING, wsdlURL.toString());
    
            portAPI = service.getPort(PORT_NAME, IMyAPI.class); 
    	}
    }
    

    public by sTiLL-iLL modified Sep 8, 2015  2775  1  6  10

    ParaFunc.cs - Parallelized Functional stuffs : Sort, Search, Map, Reduce, MapReduce

    It hardly blows anything up! LoL an experiment in functional programming
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    namespace ParaStuff
    {
    
        public class ParallelSort<T>
        {
    
            public static void ParaQuickSort (T[] data, IComparer<T> comp, int limit = 16, int minSize = 10000)
            {
                DoSort(data, 0, data.Length - 1, comp, 0, limit, minSize);
            }
    
    
            internal static void DoSort (T[] data, int start, int end, IComparer<T> comp, int curIdx, int limit, int minSize)
            {
                if (start < end)
                {
                    if (curIdx > limit || end - start < minSize)
                    {
                        Array.Sort(data, start, end - start + 1, comp);
                    }
                    else
                    {
                        int pivotAt = Sector(data, start, end, comp);
                        Task lTsk = Task.Factory.StartNew(( ) => {
                            DoSort(data, start, pivotAt - 1, comp, curIdx + 1, limit, minSize);
                        });
                        Task rTsk = Task.Factory.StartNew(( ) => {
                            DoSort(data, pivotAt + 1, end, comp, curIdx + 1, limit, minSize);
                        });
    
                        Task.WaitAll(lTsk, rTsk);
                    }
                }
            }
            
            internal static void Switch (T[] data, int firstIdx, int secondIdx)
            {
                T pxy = data[firstIdx];
                data[firstIdx] = data[secondIdx];
                data[secondIdx] = pxy;
            }
    
            internal static int Sector (T[] data, int start, int end, IComparer<T> comp)
            {
                // get the pivot and put it at the end
                T pivot = data[start];
                Switch(data, start, end);
                int saveAt = start;
    
                for (int i = start; i < end; i++)
                {
                    if (comp.Compare(data[i], pivot) <= 0)
                    {
                        Switch(data, i, saveAt);
                        saveAt++;
                    }
                }
    
                Switch(data, saveAt, end);
                return saveAt;
            }
        }
    
    
        public class Graph<T>
        {
            public Graph<T> LeftNd, RightNd;
            public T Data;
        }
    
    
        public class GraphSeeker
        {
            public static void Seek<T> (Graph<T> grph, Action<T> actn)
            {
                if (grph != null)
                {
                    actn.Invoke(grph.Data);
                    if (grph.LeftNd != null && grph.RightNd != null)
                    {
                        Task lTsk = Task.Factory.StartNew(( ) => Seek(grph.LeftNd, actn));
                        Task rTsk = Task.Factory.StartNew(( ) => Seek(grph.RightNd, actn));
                        Task.WaitAll(lTsk, rTsk);
                    }
                }
            }
        }
    
    
        public class GraphSearch
        {
            private static CancellationTokenSource tokSrc;
    
            public static T Search<T> (Graph<T> grph, Func<T, bool> searchFunc)
            {
    
                tokSrc = new CancellationTokenSource();
                GraphWrap<T> rzlt = Search(grph, searchFunc, tokSrc);
                return rzlt == null ? default(T) : rzlt.Value;
            }
    
            public class GraphWrap<T>
            {
                public T Value;
            }
    
    
            private static GraphWrap<T> Search<T> (Graph<T> grph, Func<T, bool> searchFunc, CancellationTokenSource tokSrc)
            {
                GraphWrap<T> rzlt = null;
    
                if (grph != null)
                {
                    if (searchFunc(grph.Data))
                    {
                        tokSrc.Cancel();
                        rzlt = new GraphWrap<T>()
                        {
                            Value = grph.Data
                        };
                    }
                    else
                    {
                        if (grph.LeftNode != null && grph.RightNode != null)
                        {
                            Task<GraphWrap<T>> lTsk = Task<GraphWrap<T>>.Factory.StartNew(( ) => Search(grph.LeftNode, searchFunc, tokSrc), tokSrc.Token);
                            Task<GraphWrap<T>> rTsk = Task<GraphWrap<T>>.Factory.StartNew(( ) => Search(grph.RightNode, searchFunc, tokSrc), tokSrc.Token);
                            try
                            {
                                rzlt = lTsk.Result != null ? lTsk.Result : rTsk.Result != null ? rTsk.Result : null;
                            }
                            catch (Exception)
                            {       }
                        }
                    }
                }
    
                return rzlt;
            }
        }
    
    
        public class ParallelCache<TKey, TValue>
        {
            private ConcurrentDictionary<TKey, Lazy<TValue>> catalog;
            private Func<TKey, TValue> factory;
    
            public ParallelCache (Func<TKey, TValue> fac)
            {
                factory = fac;
                catalog = new ConcurrentDictionary<TKey, Lazy<TValue>>();
            }
    
            public TValue GetCurrentVal (TKey k)
            {
                return catalog.GetOrAdd(k, new Lazy<TValue>(( ) => factory(k))).Value;
            }
        }
    
    
        public class ParaMap
        {
            public static TOutput[] PMap<TInput, TOutput> (Func<TInput, TOutput> mapFunc, TInput[] data)
            {
                return data.AsParallel().AsOrdered().Select(value => mapFunc(value)).ToArray();
            }
        }
    
    
        public class ParaReduce
        {
            public static TValue PReduce<TValue> (TValue[] src, TValue seed, Func<TValue, TValue, TValue> reduceFunc)
            {
                return src.AsParallel().Aggregate(seed, (lRzlt, val) => reduceFunc(lRzlt, val), (oRzlt, lRzlt) => reduceFunc(oRzlt, lRzlt), oRzlt => oRzlt);
            }
        }
    
    
        public class ParaMapReduce
        {
            public static IEnumerable<TOutput> PMapReduce<TInput, TIntermediate, TKey, TOutput> (IEnumerable<TInput> src, Func<TInput, IEnumerable<TIntermediate>> mapFunc, Func<TIntermediate, TKey> groupFunc, Func<IGrouping<TKey, TIntermediate>, TOutput> reduceFunc)
            {
                return src.AsParallel().SelectMany(mapFunc).GroupBy(groupFunc).Select(reduceFunc);
            }
        }
    
    
        public static class SmartSelection
        {
            public static void Calculate<TInput, TOutput> (TInput value, Action<long, TOutput> callback, params Func<TInput, TOutput>[] functions)
            {
                int cnt= 0;
                Task.Factory.StartNew(( ) => {
                  Parallel.ForEach(functions, (Func<TInput, TOutput> func, ParallelLoopState lpSt, long idx) => {
                        TOutput rez = func(value);
                        if (Interlocked.Increment(ref cnt) == 1)
                        {
                            lpSt.Stop();
                            callback(idx, rez);
                        }
                    });
                });
            }
        }
    
    
        public class SmartCache<TKey, TValue>
        {
            private ConcurrentDictionary<TKey, Lazy<TValue>> catalog;
            private BlockingCollection<TKey> roster;
            private Func<TKey, TKey[]> smartFunc;
            private Func<TKey, TValue> facFunc;
    
            public SmartCache (Func<TKey, TValue> factory, Func<TKey, TKey[]> spec)
            {
                smartFunc = spec;
                catalog = new ConcurrentDictionary<TKey, Lazy<TValue>>();
                roster = new BlockingCollection<TKey>();
    
                facFunc = (k => {
                    TValue value = factory(k);
                    roster.Add(k);
    
                    return value;
                });
    
                Task.Factory.StartNew(( ) => {
                    Parallel.ForEach(roster.GetConsumingEnumerable(),
                        new ParallelOptions
                        {
                            MaxDegreeOfParallelism = 2
                        },
                        k => {
                            // ya gotta enumerate to speculate! 
                            foreach (TKey spk in smartFunc(k))
                            {
                                TValue res = catalog.GetOrAdd(spk, new Lazy<TValue>(( ) => factory(spk))).Value;
                            }
                        });
                });
            }
    
            public TValue GetCurrentVal (TKey k)
            {
                return catalog.GetOrAdd(k, new Lazy<TValue>(( ) => facFunc(k))).Value;
            }
        }
    }
    
    
    
    namespace ParaStuff.FeedBackWindow
    {
      
      // use this specialized console for any output etc. that you need
      
        public class FeedBackWindow
        {
            private static BlockingCollection<Action> bq;
            private static Task msgThd;
    
    
            static FeedBackWindow ( )
            {
                bq = new BlockingCollection<Action>();
                msgThd = Task.Factory.StartNew(( ) =>
                {
                    foreach (Action atn in bq.GetConsumingEnumerable())
                    {
                        atn.Invoke();
                    }
                }, TaskCreationOptions.LongRunning);
            }
    
    
            public static void WriteLine (object val)
            {
                bq.Add(new Action(( ) => Console.WriteLine(val)));
            }
    
    
            public static void WriteLine (string fmt, params object[] vals)
            {
                bq.Add(new Action(( ) => Console.WriteLine(fmt, vals)));
            }
        }
    }
    
    
    namespace ParaStuff.Pipeline
    {
      
        private class Reaction
        {
            public TInput Value;
            public Action<TInput, TOutput> Callback;
        }
      
      
        public class Pipeline<TInput, TOutput>
        {
            private BlockingCollection<Reaction> valQ;
            Func<TInput, TOutput> pipelineFunc;
    
            public Pipeline (Func<TInput, TOutput> func)
            {
                pipelineFunc = func;
            }
    
            public Pipeline<TInput, TNewOutput> AddFunction<TNewOutput> (Func<TOutput, TNewOutput> newfunc)
            {
                Func<TInput, TNewOutput> frankenFunc = (dta =>
                {
                    return newfunc(pipelineFunc(dta));
                });
                return new Pipeline<TInput, TNewOutput>(frankenFunc);
            }
    
            public void AddVal (TInput val, Action<TInput, TOutput> callback)
            {
                valQ.Add(new Reaction
                {
                    Value = val,
                    Callback = callback
                });
            }
    
            public void Begin ( )
            {
                valQ = new BlockingCollection<Reaction>();
                Task.Factory.StartNew(( ) =>
                {
                    Parallel.ForEach(valQ.GetConsumingEnumerable(), rpr =>
                    {
                        rpr.Callback(rpr.Value, pipelineFunc(rpr.Value));
                    });
                });
            }
    
            public void End ( )
            {
                valQ.CompleteAdding();
            }
        }
    }
    
    
                

    public by johansonkatherine modified Mar 11, 2014  6345  1  10  5

    Save Microsoft OneNote (.one) file as an image (.PNG, .BMP, .JPEG, .GIF) file in C#/.NET

    The Aspose.Note for .NET API allows developers to open files & manipulate elements of OneNote books & export them to PNG, GIF, JPEG, BMP and PDF formats. The following code sample shows developers how to save OneNote File as an image in C#/.NET
    // Load the document into Aspose.Note.
        Document oneFile = new Document(@"FullFileName.one");
        // Save the document as GIF.
        oneFile.Save("FullFileName.gif", SaveFormat.Gif);
    	
        OR
    
        // Load the document into Aspose.Note.
        Document oneFile = new Document(@"FullFileName.one");
        // Initialize ImageSaveOptions object 
        ImageSaveOptions opts = new ImageSaveOptions(SaveFormat.Png);
        // Set page index
        opts.PageIndex = 1;
        // Save the document as PNG.
        oneFile.Save(@"FullFileName.png", opts);
    

    public by johansonkatherine modified Apr 16, 2014  4584  0  6  3

    Java code for Changing Color Space of PDF Document

    This code shows how java developers can change color space of PDF document from RGB color to CMYK and vice versa by using Aspose.PDF for Java Library. The following methods have been implemented in the Operator class for changing colors. Use it to change some specific RGB/CMYK colors to CMYK/RGB color space, keeping the remaining PDF document as it
    Document doc = new Document(myDir + "input_color.pdf");
    OperatorCollection contents = doc.getPages().get_Item(1).getContents();
    System.out.println("Values of RGB color operators in the pdf document");
    for (int j = 1; j <= contents.size(); j++)
        {
    	Operator oper = contents.get_Item(j);
    	if (oper instanceof Operator.SetRGBColor || oper instanceof Operator.SetRGBColorStroke)
    	try {
    	    //Converting RGB to CMYK color
    	    System.out.println(oper.toString());
    
    	    double[] rgbFloatArray = new double[]
    	        {
    		    	Double.valueOf(oper.getParameters().get(0).toString()),
    		    	Double.valueOf(oper.getParameters().get(1).toString()),
    		    	Double.valueOf(oper.getParameters().get(2).toString()),
    	        };
    	    double[] cmyk = new double[4];
    	    if (oper instanceof Operator.SetRGBColor)
    	    {
    		((Operator.SetRGBColor)oper).getCMYKColor(rgbFloatArray, cmyk);
    		contents.set_Item(j, new Operator.SetCMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
    		}
    		else if (oper instanceof Operator.SetRGBColorStroke)
    		{
    		    ((Operator.SetRGBColorStroke)oper).getCMYKColor(rgbFloatArray, cmyk);
    		   contents.set_Item(j, new Operator.SetCMYKColorStroke(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
    		}
    		    else
    throw new java.lang.Throwable("Unsupported command");
    
    	} catch (Throwable e) {
    	    e.printStackTrace();
    	}
    		        }
    doc.save(myDir + "input_colorout.pdf");
    
    //Testing the result
    System.out.println("Values of converted CMYK color operators in the result pdf document");
    doc = new Document(myDir + "input_colorout.pdf");
    contents = doc.getPages().get_Item(1).getContents();
    for (int j = 1; j <= contents.size(); j++)
        {
    	Operator oper = contents.get_Item(j);
    	if (oper instanceof Operator.SetCMYKColor || oper instanceof Operator.SetCMYKColorStroke)
    	{
    	   System.out.println(oper.toString());
    	}
       }
    
    • Public Snippets
    • Channels Snippets