Sunday, May 17, 2015

Make A Copy Of A Pdf File Using Java

package com.pkm.concat.two.pdf;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by pritom on 17/05/2015.
 */
public class FileToByteToFile {
    public static void main(String[] args) throws Exception {
        File file = new File("original.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        for (int readNum; (readNum = fileInputStream.read(bytes)) != -1;) {
            byteArrayOutputStream.write(bytes, 0, readNum);
        }
        byte[] bytesRead = byteArrayOutputStream.toByteArray();
        File outputFile = new File("Duplicate-" + file.getName().toLowerCase());
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(bytesRead);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

Concat Or Join Or Add Two Or More Pdf File To One Pdf FIle Using Java & Lowagie


package com.pkm.concat.two.pdf;

import java.io.*;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Created by pritom on 17/05/2015.
 */
public class ConcatTwoPdfBytes {
    public static void main(String[] args) throws Exception {
        File file = new File("from-1.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        Document document = new Document();
        Rectangle rectangle = PageSize.A4;
        document.setPageSize(rectangle);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        PdfContentByte cb = pdfWriter.getDirectContent();

        PdfReader pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }

        File file2 = new File("from-2.pdf");
        fileInputStream = new FileInputStream(file2);
        pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }
        document.close();

        byte[] bytesRead = byteArrayOutputStream.toByteArray();
        File outputFile = new File(file.getName() + " And  " + file2.getName());
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(bytesRead);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}


from-1.pdf from-2.pdf from-1.pdf And from-2.pdf Download Jar

Saturday, May 16, 2015

Java Create Watermark Text Or Fill Area To An Image


package com.pkm;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class WatermarkTextToImage {
    public static void main(String[] args) throws Exception {
 ImageIcon photo = new ImageIcon("100_6929.jpg");
 BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
  photo.getIconHeight(),
  BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

        g2d.drawImage(photo.getImage(), 0, 0, null);

        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
        g2d.setComposite(alpha);

        g2d.setColor(Color.white);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2d.setFont(new Font("Arial", Font.BOLD, 100));

        String watermark = "Pritom Kumar Mondal";

        FontMetrics fontMetrics = g2d.getFontMetrics();
        Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

        g2d.drawString(watermark,
         (photo.getIconWidth() - (int) rect.getWidth()) / 2,
         (photo.getIconHeight() - (int) rect.getHeight()) / 2);

        alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f);
        g2d.setComposite(alpha);
        g2d.setColor(Color.red);
        g2d.fillOval(0, 0, photo.getIconWidth(), photo.getIconHeight());

        //Free graphic resources
        ImageIO.write(bufferedImage, "JPEG", new File("100_6929_Watermark.JPG"));
        g2d.dispose();
    }
}

Input & Output Image Respectively

Convert RGB Values Of A Color To A Hexadecimal String And Vice Versa Using jQuery

Hex: RGB:
RGB: Hex:


/* RGB Value To Hexa Decimal */
function toHex(n) {
     n = parseInt(n);
     if (isNaN(n)) return "00";
     n = Math.max(0,Math.min(n,255));
     return "0123456789ABCDEF".charAt((n-n%16)/16)
     + "0123456789ABCDEF".charAt(n%16);
}
toHex("20");

/* Hext Decimal Value To RGB Value */
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
var str = "#34F355";
hexToR(str);
hexToG(str);
hexToB(str);

Friday, May 15, 2015

Create Zip File Using Java From List Of Files


package com.pkm.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void main(String[] args) throws Exception {
         List<String> fileList = new ArrayList<>();
         fileList.add("ImageName.png");
         fileList.add("ImageName.jpg");
         fileList.add("ImageName.gif");
         createZip(fileList, "Output.zip");
    }

    public static void createZip(List<String> fileList, String zipFileName) 
              throws Exception {
         FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
         ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
  
         for(String inputFileName : fileList) {
             File file = new File(inputFileName);
             FileInputStream fileInputStream = new FileInputStream(file);
             ZipEntry zipEntry = new ZipEntry(inputFileName);
             zipOutputStream.putNextEntry(zipEntry);

             byte[] bytes = new byte[1024];
             int length;
             while ((length = fileInputStream.read(bytes)) >= 0) {
                 zipOutputStream.write(bytes, 0, length);
             }

             zipOutputStream.closeEntry();
             fileInputStream.close();
         }
  
         zipOutputStream.close();
         fileOutputStream.close();
    }
}

Using Java Create An Image And Save To File

package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Main {
    public static void main(String args[]) throws Exception {
 try {
     int width = 200, height = 200;
     // TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
     // into integer pixels
     BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     Graphics2D ig2 = bi.createGraphics();
  
     ig2.setColor(Color.red);
     ig2.fillRect(0, 0, width, height);
  
     ig2.setColor(Color.green);
     ig2.fillOval(0, 0, width, height);
 
     Font font = new Font("TimesRoman", Font.BOLD, 80);
     ig2.setFont(font);
     String message = "PKM";
     FontMetrics fontMetrics = ig2.getFontMetrics();
     int stringWidth = fontMetrics.stringWidth(message);
     int stringHeight = fontMetrics.getAscent();
     ig2.setPaint(Color.black);
   
     ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4); 
   
     ImageIO.write(bi, "PNG", new File("ImageName.PNG"));   
     ImageIO.write(bi, "JPEG", new File("ImageName.JPG"));   
     ImageIO.write(bi, "gif", new File("ImageName.GIF"));   
     System.out.println("Image Create Done");  
 }  
 catch (Exception ex) {  
     ex.printStackTrace();  
 } 
    }
}

Output


Saturday, May 9, 2015

jQuery get an elements position or offset according to some parent element


$.fn.offsetRelative = function(top){
    var $this = $(this);
    var $parent = $this.offsetParent();
    var offset = $this.position();
    
    // add scroll
    offset.top += $this.scrollTop()+$parent.scrollTop();
    offset.left += $this.scrollLeft()+$parent.scrollLeft();
    if(!top) {
        // Didn't pass a 'top' element
        return offset;
    } else if($parent.get(0).tagName == "BODY") {
        // Reached top of document
        return offset;
    } else if($($(top), $parent).length) {
        // Parent element contains the 'top' element we want the offset to be relative to
        return offset;
    } else if($parent[0] == $(this).closest(top)[0]) {
        // Reached the 'top' element we want the offset to be relative to
        return offset;
    } else {
        // Get parent's relative offset
        var parent_offset = $parent.offsetRelative(top);
        offset.top += parent_offset.top;
        offset.left += parent_offset.left;
        return offset;
    }
};

JSFiddle link