Downloading Images Through PDFBox

RetrieveAndDownloadImages.java

package com.hari.main.imageretrieve;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.axiom.om.util.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;

import com.kwiktag.webservices.util.XmlUtil;
import com.kwiktag.webservices.util.kwiktagUtils;
import com.necho.platform.service.receiptretriever.ReceiptRetriever;
import com.necho.platform.service.receiptupload.PDFDocumentHelper;
import com.necho.platform.service.receiptupload.TIFFBilevelVerifierImpl;
import com.necho.platform.service.receiptupload.TIFFInfoVO;
import com.necho.platform.service.receiptupload.TIFFVerifier;

public class RetrieveAndDownloadImages {

private Object detail;
// static private String EMA_FORM = "EMAForm";

public Object getDetail() {
return detail;
}

private int imageWidth;

private int imageHeight;

public int getImageWidth() {
return this.imageWidth;
}

public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}

public int getImageHeight() {
return this.imageHeight;
}

public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}

public void call(String searchCode, boolean isBarcode) {
throw new UnsupportedOperationException("Not implemented.");
}

public String getContentType() {
return ReceiptRetriever.PDF_CONTENT_TYPE;
}

public byte[] getImage() {
// return Base64.decode((String) getDetail());
return ((ByteArrayOutputStream) detail).toByteArray();
}

public void downloadReceipt(String barcode, String ReceiptsDownloadPath) throws Exception {
// TODO Auto-generated method stub

System.out.println("Service Method Of ImageRetrieve Servlet Class");
String companyId = "UB450077";
String userName = "cybershifttest"; // administrator
String password = "pass.1word"; // system
String imgUrl = "http://10.140.1.122:91"; // https://kwiktagtst1.cybershift.net
String drawerName = "Cybershift Test";
// String barcode = null; // SRIJ000111112190238 SRIJ000111112190242
System.out.println(barcode);
String versionsXML = "";
// PrintWriter outconsole = response.getWriter();
List<Short> versionList = null;
int receiptMerged = 0;

PDDocument document = new PDDocument();
List<PDDocument> documentList = new ArrayList<PDDocument>();
// String callingId = "a146a81b-f991-4d9d-904b-c9ac643d04a7";

try {
System.out.println("Start Time getting versionXML " + new Date().toString());
versionsXML = kwiktagUtils.retrieveImageVersions(companyId, userName, password, imgUrl, barcode,
drawerName);
System.out.println("End Time getting versionXML " + new Date().toString());
// System.out.println(versionsXML);
// out.println(versionsXML);

} catch (Exception e) {
System.out.println(e);
}

if (versionsXML != null && XmlUtil.isSuccess(versionsXML)) {

versionList = XmlUtil.getVersions("/KwikTag/Version", versionsXML);
System.out.println("Document [" + barcode + "] has got [" + versionList.size() + "] receipts");
System.out.println(
"Starting merging retrieved images for barcode" + barcode + " Time is :" + new Date().toString());
for (int i = versionList.size() - 1; i >= 0; i--) {

short version = versionList.get(i).shortValue();
System.out
.println("StartTime Getting " + version + " From kwiktag Service call" + new Date().toString());
String objectXML = null;
try {
objectXML = kwiktagUtils.retrieveImage(companyId, userName, password, imgUrl, barcode, drawerName,
version);
} catch (Exception e) {
System.out.println("Exception caught when calling retrieveImage");
return;
}
System.out.println(
"EndTime of Getting " + version + " From kwiktag Service call" + new Date().toString());
String type = XmlUtil.getDetail("/KwikTag/Extension", objectXML);
byte[] bytes = Base64.decode(XmlUtil.getDetail("/KwikTag/Image", objectXML));

try {
System.out.println("Document [" + barcode + "]: started processing [" + (i + 1)
+ "] receipt with type [" + type + "]");

type = "." + type;
if (PDFDocumentHelper.isTypePNG(type) || PDFDocumentHelper.isTypeJPG(type)
|| PDFDocumentHelper.isTypeGIF(type) || PDFDocumentHelper.isTypeBMP(type)) {
PDFDocumentHelper.addImageToPDF(document, bytes, type, "");
++receiptMerged;
} else if (PDFDocumentHelper.isTypeTIFF(type)) {
TIFFVerifier verifier = new TIFFBilevelVerifierImpl();
TIFFInfoVO tiffInfo = new TIFFInfoVO();
try {
InputStream bis = new ByteArrayInputStream(bytes);
tiffInfo = verifier.getTIFFInfo(bis);
} catch (Exception e) {
System.out.println(e);
}

PDFDocumentHelper.addTIFFToPDF(document, bytes, tiffInfo, "");
++receiptMerged;
} else if (PDFDocumentHelper.isTypePDF(type)) {
PDDocument addedDoc = PDFDocumentHelper.addPDFToPDF(document, bytes, "");
if (addedDoc != null) {
documentList.add(addedDoc);
}
++receiptMerged;
} else {
System.out.println("Barcode [" + barcode + "]: Failed to process [" + (i + 1)
+ "] receipt. Unsupported file type " + type);
}
System.out.println("Barcode [" + barcode + "]: completed processing [" + (i + 1)
+ "] receipt with type [" + type + "]");
} catch (Exception e) {
System.out.println("Barcode [" + barcode + "]: Failed to process [" + (i + 1)
+ "] receipt with type [" + type + "]");
System.out.println(e.getMessage() + e);
}

}
System.out.println("Finished merging retrieved images for barcode " + barcode
+ " to PDF. Number of receipts merged: " + receiptMerged + " Time is :" + new Date().toString());

}

try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileOutputStream fout1 = new FileOutputStream(ReceiptsDownloadPath + "\\" + barcode + ".pdf");

PDDocumentCatalog catalog = document.getDocumentCatalog();
List<PDPage> pageList = catalog.getAllPages();
float width = 0;
float height = 0;
for (PDPage page : pageList) {
PDRectangle rect = page.getMediaBox();
if (rect.getWidth() > width) {
width = rect.getWidth();
}
height += rect.getHeight();
}
this.setImageWidth((int) width);
this.setImageHeight((int) height);

document.save(out);
out.writeTo(fout1);
detail = out;
} catch (Exception e) {
System.out.println(e + "Exception here sree");
}

System.out.println("Completed processing retrieved images from KwikTag. Successfully processed ["
+ receiptMerged + "] receipt(s)");

String imgId = barcode;

// ServletOutputStream outStream = response.getOutputStream();

System.out.println("Receipts retrieved successfully for [" + imgId + "]. ");
System.out.println("Start sending receipt images for [" + imgId + "] to browser");

// The IE7 control that displays PDF requires the PDF to be in cache.
/*
* response.setHeader("Pragma", ""); response.setHeader("Cache-control",
* "private");
*
* response.setContentType(this.getContentType());
*/ byte[] encodedImage = this.getImage();
// outStream.write(encodedImage);

System.out.println("Finished sending receipt images for [" + imgId + "] to browser");

// outStream.flush();
// outStream.close();

}

}




XmlUtil.java

package com.kwiktag.webservices.util;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * XML utility for parsing the KwikTag result
 */
public class XmlUtil {
private final static String M_COMMON_SERVICE_ERROR = "M-Common-ServiceError";

private final static String SUCCESS_PATH = "/KwikTag/Success";

private final static String ERROR_DESCRIPTION_PATH = "/KwikTag/Error/Description";
private final static String EXTENSION_PATH = "/KwikTag/Extension";

/**
* Return the value associated to the XML element
* @param xPathQuery
*            the path to the XML element
* @param xmlResults
*            the XML to parse
* @return the XML element value
*/
public static String getDetail(String xPathQuery, String xmlResults) {
String result = null;

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new org.xml.sax.InputSource(new StringReader(xmlResults)));

Node node = XPathAPI.selectSingleNode(document.getFirstChild(), xPathQuery);
if (node != null) {
result = node.getFirstChild().getNodeValue();
}
return result;
} catch (Exception e) {

return M_COMMON_SERVICE_ERROR;
}
}

public static List<Short> getVersions(String xPathQuery, String xmlResults) {
List<Short> versions = new ArrayList<Short>();

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);

org.xml.sax.InputSource input = new org.xml.sax.InputSource(new StringReader(xmlResults));
Document document = factory.newDocumentBuilder().parse(input);

NodeList nodelist = XPathAPI.selectNodeList(document, xPathQuery);

for (int i = 0; i < nodelist.getLength(); i++) {
Element element = (Element) nodelist.item(i);
versions.add(Short.valueOf(element.getFirstChild().getFirstChild().getNodeValue()));
}
} catch (Exception e) {
versions = null;
}

return versions;
}

public static List<String> getDetails(String xpath, String xmlResults, String attribute) {

List<String> elements = new ArrayList<String>();
try {
// Create a DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader r = new StringReader(xmlResults);
org.xml.sax.InputSource is = new org.xml.sax.InputSource(r);
Document document = builder.parse(is);

NodeList nodelist = XPathAPI.selectNodeList(document, xpath);

for (int i = 0; i < nodelist.getLength(); i++) {
// Get element
Element elem = (Element) nodelist.item(i);
String barcode = elem.getAttribute(attribute);
elements.add(barcode);

}
return elements;
} catch (Exception e) {

return Collections.emptyList();
}
}

public static boolean isSuccess(String xPathQuery, String xmlResults) {
String value = getDetail(xPathQuery, xmlResults);
return "true".equalsIgnoreCase(value.trim());
}

public static boolean isSuccess(String xmlResults) {
String value = getDetail(SUCCESS_PATH, xmlResults);
return "true".equalsIgnoreCase(value.trim());
}

public static String getErrorMessage(String xmlResults) {
return getDetail(ERROR_DESCRIPTION_PATH, xmlResults);
}

public static String getErrorMessage(String xPathQuery, String xmlResults) {
return getDetail(xPathQuery, xmlResults);
}

public static String getImageExtension(String xPathQuery, String xmlResults) {
return getDetail(xPathQuery, xmlResults);
}

public static String getImageExtension(String xmlResults) {
return getDetail(EXTENSION_PATH, xmlResults);
}
}

Comments

Popular posts from this blog

CSM Quiz -2

Enabling WL-Proxy-SSL HTTP header in WebLogic

CSM Quiz -1