DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    //Following is a sample application which can be used to access the detail of contacts in all the groups.

// C# Code Sample

 
string username = "username";
string email = "email@gmail.com";
string password = "password";
string clientId = "clientid";
string clientSecret = "client secret";
string refresh_token = "refresh token";

//The refresh_token is to be used in below.
GoogleTestUser user = new GoogleTestUser(
                username,
                email,
                password,
                clientId,     //client id
                clientSecret,     //client secret
                refresh_token);   //refresh token

using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken))
{
    Contact[] contacts = client.GetAllContacts();
    foreach (Contact contact in contacts)
        Console.WriteLine(contact.DisplayName + ", " + contact.EmailAddresses[0]);

    //Fetch contacts from a specific group
    FeedEntryCollection groups = client.FetchAllGroups();
    GmailContactGroup group = null;
    foreach (GmailContactGroup g in groups)
        switch (g.Title)
        {
            case "TestGroup":
                group = g;
                break;
        }

    //Retrieve contacts from the Group
    if (group != null)
    {
        Contact[] contacts2 = client.GetContactsFromGroup(group);
        foreach (Contact con in contacts2)
            Console.WriteLine(con.DisplayName + "," + con.EmailAddresses[0].ToString());
    }
}
}
 
//VB.NET Code Sample

Dim username As String = "username"
Dim email As String = "email@gmail.com"
Dim password As String = "password"
Dim clientId As String = "client id"
Dim clientSecret As String = "client secret"
Dim refresh_token As String = "refresh token"

'The refresh_token is to be used in below.
'client id
'client secret
Dim user As New GoogleTestUser(username, email, password, clientId, clientSecret, refresh_token)
'refresh token
Using client As IGmailClient = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken)
	Dim contacts As Contact() = client.GetAllContacts()
	For Each contact As Contact In contacts
		Console.WriteLine(contact.DisplayName + ", " + contact.EmailAddresses(0))
	Next

	'Fetch contacts from a specific group
	Dim groups As FeedEntryCollection = client.FetchAllGroups()
	Dim group As GmailContactGroup = Nothing
	For Each g As GmailContactGroup In groups
		Select Case g.Title
			Case "TestGroup"
				group = g
				Exit Select
		End Select
	Next

	'Retrieve contacts from the Group
	If group IsNot Nothing Then
		Dim contacts2 As Contact() = client.GetContactsFromGroup(group)
		For Each con As Contact In contacts2
			Console.WriteLine(con.DisplayName + "," + con.EmailAddresses(0).ToString())
		Next
	End If
End Using

//Creating Gmail Contact

//C# Code Sample

string username = "newcustomeroffnet";
string email = "newcustomeroffnet@gmail.com";
string password = "visual2010";
string clientId = "633643385868-v64nsvkmh5ca2dlhkroo8941ne92onov.apps.googleusercontent.com";
string clientSecret = "UQ26EXvvo8L12TNhtLtYbHVO";
string refresh_token = "1/yord7s4aqV8t7S_vT9IqlBO60eIE-hY0WHLfqQ9zOCQ";

//The refresh_token is to be used in below.
GoogleTestUser user = new GoogleTestUser(
                username,
                email,
                password,
                clientId,     //client id
                clientSecret,     //client secret
                refresh_token);   //refresh token

//Gmail Client
IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken, user.EMail);

//Create a Contact
Contact contact = new Contact();
contact.Prefix = "Prefix";
contact.GivenName = "GivenName";
contact.Surname = "Surname";
contact.MiddleName = "MiddleName";
contact.DisplayName = "Test User 1";
contact.Suffix = "Suffix";

contact.JobTitle = "JobTitle";
contact.DepartmentName = "DepartmentName";
contact.CompanyName = "CompanyName";
contact.Profession = "Profession";

contact.Notes = "Notes";

PostalAddress address = new PostalAddress();
address.Category = PostalAddressCategory.Work;
address.Address = "Address";
address.Street = "Street";
address.PostOfficeBox = "PostOfficeBox";
address.City = "City";
address.StateOrProvince = "StateOrProvince";
address.PostalCode = "PostalCode";
address.Country = "Country";
contact.PhysicalAddresses.Add(address);

PhoneNumber pnWork = new PhoneNumber();
pnWork.Number = "323423423423";
pnWork.Category = PhoneNumberCategory.Work;
contact.PhoneNumbers.Add(pnWork);
PhoneNumber pnHome = new PhoneNumber();
pnHome.Number = "323423423423";
pnHome.Category = PhoneNumberCategory.Home;
contact.PhoneNumbers.Add(pnHome);
PhoneNumber pnMobile = new PhoneNumber();
pnMobile.Number = "323423423423";
pnMobile.Category = PhoneNumberCategory.Mobile;
contact.PhoneNumbers.Add(pnMobile);

contact.Urls.Blog = "Blog.ru";
contact.Urls.BusinessHomePage = "BusinessHomePage.ru";
contact.Urls.HomePage = "HomePage.ru";
contact.Urls.Profile = "Profile.ru";

contact.Events.Birthday = DateTime.Now.AddYears(-30);
contact.Events.Anniversary = DateTime.Now.AddYears(-10);

contact.InstantMessengers.AIM = "AIM";
contact.InstantMessengers.GoogleTalk = "GoogleTalk";
contact.InstantMessengers.ICQ = "ICQ";
contact.InstantMessengers.Jabber = "Jabber";
contact.InstantMessengers.MSN = "MSN";
contact.InstantMessengers.QQ = "QQ";
contact.InstantMessengers.Skype = "Skype";
contact.InstantMessengers.Yahoo = "Yahoo";

contact.AssociatedPersons.Spouse = "Spouse";
contact.AssociatedPersons.Sister = "Sister";
contact.AssociatedPersons.Relative = "Relative";
contact.AssociatedPersons.ReferredBy = "ReferredBy";
contact.AssociatedPersons.Partner = "Partner";
contact.AssociatedPersons.Parent = "Parent";
contact.AssociatedPersons.Mother = "Mother";
contact.AssociatedPersons.Manager = "Manager";

//Email Address
EmailAddress eAddress = new EmailAddress();
eAddress.Address = "email@gmail.com";
contact.EmailAddresses.Add(eAddress);

string contactUri = client.CreateContact(contact);

//VB.NET Code Sample

Dim username As String = "newcustomeroffnet"
Dim email As String = "newcustomeroffnet@gmail.com"
Dim password As String = "visual2010"
Dim clientId As String = "633643385868-v64nsvkmh5ca2dlhkroo8941ne92onov.apps.googleusercontent.com"
Dim clientSecret As String = "UQ26EXvvo8L12TNhtLtYbHVO"
Dim refresh_token As String = "1/yord7s4aqV8t7S_vT9IqlBO60eIE-hY0WHLfqQ9zOCQ"

'The refresh_token is to be used in below.
'client id
'client secret
Dim user As New GoogleTestUser(username, email, password, clientId, clientSecret, refresh_token)
'refresh token
'Gmail Client
Dim client As IGmailClient = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken, user.EMail)

'Create a Contact
Dim contact As New Contact()
contact.Prefix = "Prefix"
contact.GivenName = "GivenName"
contact.Surname = "Surname"
contact.MiddleName = "MiddleName"
contact.DisplayName = "Test User 1"
contact.Suffix = "Suffix"

contact.JobTitle = "JobTitle"
contact.DepartmentName = "DepartmentName"
contact.CompanyName = "CompanyName"
contact.Profession = "Profession"

contact.Notes = "Notes"

Dim address As New PostalAddress()
address.Category = PostalAddressCategory.Work
address.Address = "Address"
address.Street = "Street"
address.PostOfficeBox = "PostOfficeBox"
address.City = "City"
address.StateOrProvince = "StateOrProvince"
address.PostalCode = "PostalCode"
address.Country = "Country"
contact.PhysicalAddresses.Add(address)

Dim pnWork As New PhoneNumber()
pnWork.Number = "323423423423"
pnWork.Category = PhoneNumberCategory.Work
contact.PhoneNumbers.Add(pnWork)
Dim pnHome As New PhoneNumber()
pnHome.Number = "323423423423"
pnHome.Category = PhoneNumberCategory.Home
contact.PhoneNumbers.Add(pnHome)
Dim pnMobile As New PhoneNumber()
pnMobile.Number = "323423423423"
pnMobile.Category = PhoneNumberCategory.Mobile
contact.PhoneNumbers.Add(pnMobile)

contact.Urls.Blog = "Blog.ru"
contact.Urls.BusinessHomePage = "BusinessHomePage.ru"
contact.Urls.HomePage = "HomePage.ru"
contact.Urls.Profile = "Profile.ru"

contact.Events.Birthday = DateTime.Now.AddYears(-30)
contact.Events.Anniversary = DateTime.Now.AddYears(-10)

contact.InstantMessengers.AIM = "AIM"
contact.InstantMessengers.GoogleTalk = "GoogleTalk"
contact.InstantMessengers.ICQ = "ICQ"
contact.InstantMessengers.Jabber = "Jabber"
contact.InstantMessengers.MSN = "MSN"
contact.InstantMessengers.QQ = "QQ"
contact.InstantMessengers.Skype = "Skype"
contact.InstantMessengers.Yahoo = "Yahoo"

contact.AssociatedPersons.Spouse = "Spouse"
contact.AssociatedPersons.Sister = "Sister"
contact.AssociatedPersons.Relative = "Relative"
contact.AssociatedPersons.ReferredBy = "ReferredBy"
contact.AssociatedPersons.Partner = "Partner"
contact.AssociatedPersons.Parent = "Parent"
contact.AssociatedPersons.Mother = "Mother"
contact.AssociatedPersons.Manager = "Manager"

'Email Address
Dim eAddress As New EmailAddress()
eAddress.Address = "email@gmail.com"
contact.EmailAddresses.Add(eAddress)

Dim contactUri As String = client.CreateContact(contact)

//Update Gmail Contact

//Once a contact is retrieved, its attributes can be updated and the contact can be saved back to the Gmail account. The sample code below retrieves contacts from a Gmail account and then modifies one of these which is then saved back.

//C# Code Sample

string username = "username";
string email = "email@gmail.com";
string password = "password";
string clientId = "clientid";
string clientSecret = "client secret";
string refresh_token = "refresh token";

//The refresh_token is to be used in below.
GoogleTestUser user = new GoogleTestUser(
                username,
                email,
                password,
                clientId,     //client id
                clientSecret,     //client secret
                refresh_token);   //refresh token

using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken))
{
    Contact[] contacts = client.GetAllContacts();
    Contact contact = contacts[0];
    contact.JobTitle = "Manager IT";
    contact.DepartmentName = "Customer Support";
    contact.CompanyName = "Aspose";
    contact.Profession = "Software Developer";
    client.UpdateContact(contact);
}

//Deleting a Gmail Contact

//C# Code Sample

client.DeleteContact(contact.Id.GoogleId);

//Saving a Contact

//C# Code Sample

contact.Save("contact.msg", ContactSaveFormat.Msg);
contact.Save("contact.vcf", ContactSaveFormat.VCard);
                
                    COPY table_name  TO 'D:/.../csf_hile.csv' DELIMITER ';' CSV HEADER;                
                    //Below is a complete Java program that generates and recognizes barcodes from Microsoft Word documents.   

 //[Java]
import com.aspose.barcode.*;
import com.aspose.barcoderecognition.BarCodeReadType;
import com.aspose.barcoderecognition.BarCodeReader;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImageType;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeType;
import com.aspose.words.Shape;
import java.awt.Toolkit;
import java.text.MessageFormat;

public class RecognitionFromWord {
    public static void main(String[] args)
    {
        try
        {
            // Generate barcode image
            BarCodeBuilder builder = new BarCodeBuilder();
            builder.setSymbologyType(Symbology.Code39Standard);
            builder.setCodeText("test-123");
            String strBarCodeImageSave = "img.jpg";
            builder.save(strBarCodeImageSave);

            // Add the image to a Word doc
            Document doc = new Document();
            DocumentBuilder docBuilder = new DocumentBuilder(doc);
            docBuilder.insertImage(strBarCodeImageSave);
            String strWordFile = "docout.doc";
            doc.save(strWordFile);

            // Recognition part
            // Extract image from the Word document
            NodeCollection<Shape> shapes = doc.getChildNodes(NodeType.SHAPE, true, false);
            int imageIndex = 0;

            for(Shape shape :  shapes)
            {
                if (shape.hasImage())
                {
                    // If this shape is an image, extract image to file
                    String extension = ImageTypeToExtension(shape.getImageData().getImageType());
                    String imageFileName = MessageFormat.format("Image.ExportImages.{0} Out.{1}", imageIndex, extension);
                    String strBarCodeImageExtracted = "" + imageFileName;
                    shape.getImageData().save(strBarCodeImageExtracted);

                    // Recognize barcode from this image
                    BarCodeReader reader = new BarCodeReader(Toolkit.getDefaultToolkit().getImage(strBarCodeImageExtracted),BarCodeReadType.Code39Standard);
                    while (reader.read())
                    {
                        System.out.println("codetext: " + reader.getCodeText());
                    }
                    imageIndex++;
                }
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }

    private static String ImageTypeToExtension(int imageType) throws Exception
    {
        switch (imageType)
        {
            case ImageType.BMP:
                return "bmp";
            case ImageType.EMF:
                return "emf";
            case ImageType.JPEG:
                return "jpeg";
            case ImageType.PICT:
                return "pict";
            case ImageType.PNG:
                return "png";
            case ImageType.WMF:
                return "wmf";
            default:
                throw new Exception("Unknown image type.");
        }
    }

}

                
                    //Adding Slides to the Presentation

//[C# Code Sample]
 
//Instantiate Presentation class that represents the presentation file

public static void AddLayoutSlide()
{
    string n = @"Test.pptx";
    //Instantiate Presentation class that represents the presentation file
    using (Presentation p = new Presentation(n))
    {
        // Try to search by layout slide type
        IMasterLayoutSlideCollection layoutSlides = p.Masters[0].LayoutSlides;
        ILayoutSlide layoutSlide =
            layoutSlides.GetByType(SlideLayoutType.TitleAndObject) ??
            layoutSlides.GetByType(SlideLayoutType.Title);

        if (layoutSlide == null)
        {
            // The situation when a presentation doesn't contain some type of layouts.
            // Technographics.pptx presentation only contains Blank and Custom layout types.
            // But layout slides with Custom types has different slide names,
            // like "Title", "Title and Content", etc. And it is possible to use these
            // names for layout slide selection.
            // Also it is possible to use the set of placeholder shape types. For example,
            // Title slide should have only Title pleceholder type, etc.
            foreach (ILayoutSlide titleAndObjectLayoutSlide in layoutSlides)
            {
                if (titleAndObjectLayoutSlide.Name == "Title and Object")
                {
                    layoutSlide = titleAndObjectLayoutSlide;
                    break;
                }
            }
            if (layoutSlide == null)
            {
                foreach (ILayoutSlide titleLayoutSlide in layoutSlides)
                {
                    if (titleLayoutSlide.Name == "Title")
                    {
                        layoutSlide = titleLayoutSlide;
                        break;
                    }
                }
                if (layoutSlide == null)
                {
                    layoutSlide = layoutSlides.GetByType(SlideLayoutType.Blank);
                    if (layoutSlide == null)
                    {
                        layoutSlide = layoutSlides.Add(SlideLayoutType.TitleAndObject, "Title and Object");
                    }
                }
            }
        }
        
        //Adding empty slide with added layout slide 
        p.Slides.InsertEmptySlide(0, layoutSlide);

        //Save presentation    
        p.Save(n + "_output.pptx", SaveFormat.Pptx);
    }
} 
 
//VB.NET Code Sample
 
Public Shared Sub AddLayoutSlide()
    Dim n As String = "Technographics.pptx"
   'Instantiate Presentation class that represents the presentation file
    Using p As New Presentation(n)
    ' Try to search by layout slide type
        Dim layoutSlides As IMasterLayoutSlideCollection = p.Masters(0).LayoutSlides
        Dim layoutSlide As ILayoutSlide = If(layoutSlides.GetByType(SlideLayoutType.TitleAndObject), layoutSlides.GetByType(SlideLayoutType.Title))

        If layoutSlide Is Nothing Then
            ' The situation when a presentation doesn't contain some type of layouts.
            ' Technographics.pptx presentation only contains Blank and Custom layout types.
            ' But layout slides with Custom types has different slide names,
            ' like "Title", "Title and Content", etc. And it is possible to use these
            ' names for layout slide selection.
            ' Also it is possible to use the set of placeholder shape types. For example,
            ' Title slide should have only Title pleceholder type, etc.
            For Each titleAndObjectLayoutSlide As ILayoutSlide In layoutSlides
                If titleAndObjectLayoutSlide.Name = "Title and Object" Then
                    layoutSlide = titleAndObjectLayoutSlide
                    Exit For
                End If
            Next
            If layoutSlide Is Nothing Then
                For Each titleLayoutSlide As ILayoutSlide In layoutSlides
                    If titleLayoutSlide.Name = "Title" Then
                        layoutSlide = titleLayoutSlide
                        Exit For
                    End If
                Next
                If layoutSlide Is Nothing Then
                    layoutSlide = layoutSlides.GetByType(SlideLayoutType.Blank)
                    If layoutSlide Is Nothing Then
                        layoutSlide = layoutSlides.Add(SlideLayoutType.TitleAndObject, "Title and Object")
                    End If
                End If
            End If
        End If

        ' Adding new slide with added layout
        p.Slides.InsertEmptySlide(0, layoutSlide)

        ' Save presentation
        p.Save(n & "_output.pptx", SaveFormat.Pptx)
    End Using
End Sub
                
                        public Advice retryAdvice(long initialInterval, double multiplier, long maxInterval, int maxAttempts) {
        Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();
        // the class to look for and whether to retry when found
        retryableExceptions.put(SomeSpecialException.class, true);
        // the final boolean indicates whether to search the whole stacktrace for the exception
        SimpleRetryPolicy srp = new SimpleRetryPolicy(maxAttempts, retryableExceptions, true);

        return StatelessRetryInterceptorBuilder.stateless().retryPolicy(srp).backOffOptions(initialInterval, multiplier,
                maxInterval).recoverer(yourCustomRecoverer).build();
    }                
                       /**
     * {@inheritDoc} Displays a file chooser dialog
     * and opens the selected files.
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (running) {
            return;
        }
        try {
            running = true;
            JFileChooser chooser = prepareFileChooser();
            File[] files;
            try {
                if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
                    String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N
                    System.setProperty("apple.awt.fileDialogForDirectories", "false"); //NOI18N
                    FileDialog fileDialog = new FileDialog(WindowManager.getDefault().getMainWindow());
                    fileDialog.setMode(FileDialog.LOAD);
                    fileDialog.setDirectory(getCurrentDirectory().getAbsolutePath());
                    fileDialog.setTitle(chooser.getDialogTitle());
                    fileDialog.setVisible(true);
                    if( null != oldFileDialogProp ) {
                        System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N
                    } else {
                        System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N
                    }

                    if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) {
                        String selFile = fileDialog.getFile();
                        File dir = new File( fileDialog.getDirectory() );
                        files = new File[] { new File( dir, selFile ) };
                        currentDirectory = dir;
                    } else {
                        throw new UserCancelException();
                    }
                } else {
                    files = chooseFilesToOpen(chooser);
                    currentDirectory = chooser.getCurrentDirectory();
                    if (chooser.getFileFilter() != null) { // #227187
                        currentFileFilter =
                                chooser.getFileFilter().getDescription();
                    }
                }
            } catch (UserCancelException ex) {
                return;
            }
            for (int i = 0; i < files.length; i++) {
                OpenFile.openFile(files[i], -1);
            }
        } finally {
            running = false;
        }
    }                
                    package ph.web.action;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;


@ParentPackage(value = "showcase")
@Result(name="success",  type="redirect", location="user-login.action")
public class Index extends ActionSupport   {

	private static final long serialVersionUID = 1L;
	
	public String Execute()  {
         return SUCCESS;
        }
    
  }
                
                    package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
    {
        // Create Aspose.Words.Document and DocumentBuilder.
        // The builder makes it simple to add content to the document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // Load images from the disk using the approriate reader.
        // The file formats that can be loaded depends on the image readers available on the machine.
        ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
        ImageReader reader = ImageIO.getImageReaders(iis).next();
        reader.setInput(iis, false);

        try
        {
            // Get the number of frames in the image.
            int framesCount = reader.getNumImages(true);

            // Loop through all frames.
            for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
            {
                // Insert a section break before each new page, in case of a multi-frame image.
                if (frameIdx != 0)
                    builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

                // Select active frame.
                BufferedImage image = reader.read(frameIdx);

                // We want the size of the page to be the same as the size of the image.
                // Convert pixels to points to size the page to the actual image size.
                PageSetup ps = builder.getPageSetup();

                ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
                ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));

                // Insert the image into the document and position it at the top left corner of the page.
                builder.insertImage(
                    image,
                    RelativeHorizontalPosition.PAGE,
                    0,
                    RelativeVerticalPosition.PAGE,
                    0,
                    ps.getPageWidth(),
                    ps.getPageHeight(),
                    WrapType.NONE);
            }
        }

        finally {
            if (iis != null) {
                iis.close();
                reader.dispose();
            }
        }

        // Save the document to PDF.
        doc.save(outputFileName);
    }
} 

//Converts large size image into a PDF document

//When the size of image is bigger than max allowed size of MS Word page, an exception is thrown or image is not visible in output document. The measurement for images must be between 0 and 55.88 cm (55.88 cm = 1584 points). In this case, use the following code example.
package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    	public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
	{
	    // Create Aspose.Words.Document and DocumentBuilder.
	    // The builder makes it simple to add content to the document.
	    Document doc = new Document();
	    DocumentBuilder builder = new DocumentBuilder(doc);

	    // Load images from the disk using the approriate reader.
	    // The file formats that can be loaded depends on the image readers available on the machine.
	    ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
	    ImageReader reader = ImageIO.getImageReaders(iis).next();
	    reader.setInput(iis, false);

	    try
	    {
	        // Get the number of frames in the image.
	        int framesCount = reader.getNumImages(true);

	        // Loop through all frames.
	        for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
	        {
	            // Insert a section break before each new page, in case of a multi-frame image.
	            if (frameIdx != 0)
	                builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

	            // Select active frame.
	            BufferedImage image = reader.read(frameIdx);

	            // Max page size
	            double maxPageHeight = 1584;
	            double maxPageWidth = 1584;

	            double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
	            double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());

	            if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
	            {

	                // Get max image size.
	            	 double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight, currentImageWidth);
	            	 currentImageWidth = size[0];
	            	 currentImageHeight = size[1];
	            }

	            // We want the size of the page to be the same as the size of the image.
	            // Convert pixels to points to size the page to the actual image size.
	            PageSetup ps = builder.getPageSetup();

	            ps.setPageWidth(currentImageWidth);
	            ps.setPageHeight(currentImageHeight);

	            // Insert the image into the document and position it at the top left corner of the page.
	            Shape shape = builder.insertImage(
	                image,
	                RelativeHorizontalPosition.PAGE,
	                0,
	                RelativeVerticalPosition.PAGE,
	                0,
	                ps.getPageWidth(),
	                ps.getPageHeight(),
	                WrapType.NONE);

	            resizeLargeImage(shape);
	        }
	    }

	    finally {
	        if (iis != null) {
	            iis.close();
	            reader.dispose();
	        }
	    }

	    // Save the document to PDF.
	    doc.save(outputFileName);
	}

	public static double[] CalculateImageSize(BufferedImage img, double containerHeight,  double containerWidth, double targetHeight, double targetWidth) throws Exception {

	 targetHeight = containerHeight;
	 targetWidth = containerWidth;

	  //Get size of an image
	    double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
	    double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());

	    if (imgHeight < targetHeight && imgWidth < targetWidth)
	    {
	        targetHeight = imgHeight;
	        targetWidth = imgWidth;
	    }
	    else
	    {
	        //Calculate size of an image in the document
	        double ratioWidth = imgWidth / targetWidth;
	        double ratioHeight = imgHeight / targetHeight;
	        if (ratioWidth > ratioHeight)
	            targetHeight = (targetHeight * (ratioHeight / ratioWidth));
	        else
	            targetWidth = (targetWidth * (ratioWidth / ratioHeight));
	    }

	    double[] size = new double[2];

	    size[0] = targetWidth; //width
	    size[1] = targetHeight; //height

	    return(size);
	}

    public static void resizeLargeImage(Shape image) throws Exception
    {
        // Return if this shape is not an image.
        if (!image.hasImage())
            return;

        // Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
        PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
        double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
        double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();

        // Is one of the sides of this image too big for the page?
        ImageSize size = image.getImageData().getImageSize();
        boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;

        if (exceedsMaxPageSize)
        {
            // Calculate the ratio to fit the page size based on which side is longer.
            boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
            double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();

            // Set the new size.
            image.setWidth(size.getWidthPoints() * ratio);
            image.setHeight(size.getHeightPoints() * ratio);
        }
    }
}
                
                    package com.pky.com;

public class StaticExample {
	public static String company = "Infosys Limited";
	public String name;
	public int id;

	public StaticExample(String name, int id) {
		this.name = name;
		this.id = id;
	}

	public void show() {
		System.out.println("Employee Name :" + name + "\nEmployee Id :" + id
				+ "\nEmployee company :" + company);
	}

	public static void main(String arg[]) {
		StaticExample se = new StaticExample("Pradeep Yadav", 99231);
		se.show();

	}
}


Output :

Employee Name :Pradeep Yadav
Employee Id :99231
Employee company :Infosys Limited                
                    Here we are using OR operator so it will return only unique value. If you need to add duplicacy too use + operator. 

#!/usr/local/bin/ruby -w


class Abc

  def display

      arr1=Array(1..10);

      arr2=Array(7..15);

      arr3=arr1|arr2;

      puts "Elements of third array are :";

      arr3.each{|i| puts i};

 
 end

end

abc=Abc.new

abc.display

Output :
Elements of third array are :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15