Search This Blog

Thursday, February 4, 2010

printing applet using pdfp and jpedal

import etanah.applet.PdfPrint;
import etanah.applet.PrintWithJPedal;
import etanah.applet.util.FileUtil;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterJob;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Vector;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

/**
*
* @author don
*/
public class PrintApplet extends JApplet implements ActionListener, ChangeListener, MouseListener {

BorderLayout borderLayout1 = new BorderLayout();
JButton printButton = new JButton(“Cetak”);
Color defaultBgColor = Color.lightGray;
Cookie cookies[] = null;
String uploadAction = “”;
private String tmpFolder = System.getProperty(“java.io.tmpdir”);
FileUtil util = new FileUtil(tmpFolder);
private PrinterJob pjob = null;
private String method = “pdfp”;
Logger log = Logger.getLogger(PrintApplet.class.getSimpleName());
public String remove = “”;

// public PrintApplet() {
// init();
// }
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
@Override
public void init() {
System.out.println(“start init()…”);
// TODO start asynchronous download of heavy resources
Container c = getContentPane();
c.setLayout(new FlowLayout());
printButton.addActionListener(this);
if (getParameter(“uploadAction”) != null) {
uploadAction = getParameter(“uploadAction”);
}
if (getParameter(“method”) != null) {
method = getParameter(“method”);
}
String host = this.getCodeBase().getHost();
if (host.indexOf(“.”) != -1) {
//discard anything before first dot(.)
host = host.substring(host.indexOf(“.”));
}
Vector v = new Vector();
for (int i = 0; i < 50; i++) {
if (getParameter(“Cookie” + i) != null) {
String cookieStr = getParameter(“Cookie” + i);
String name = cookieStr.substring(0, cookieStr.indexOf(“=”));
String value = cookieStr.substring(cookieStr.indexOf(“=”) + 1);
Cookie mycookie = new Cookie(host, name, value, “/”, null, false);
v.add(mycookie);
System.out.println(“mycookie: ” + mycookie);
} else {
break;
}
}
cookies = new Cookie[v.size()];
for (int i = 0; i < cookies.length; i++) {
cookies[i] = (Cookie) v.get(i);
}
System.out.println(“uploadAction::” + uploadAction);
System.out.println(“method::” + method);
c.add(printButton);
// generate();
}

@SuppressWarnings(“static-access”)
private void generate() {
try {
final InputStream exe_file = PrintApplet.class.getResourceAsStream(“/pdfp.exe”);
final File out = new File(tmpFolder + (tmpFolder.endsWith(File.separator) ? “” : File.separator) + “pdfp.exe”);

AccessController.doPrivileged(
new PrivilegedAction() {

public Object run() {
try {
if (!out.exists()) {
util.copyFile(exe_file, out);
}
return “”;
} catch (Exception ex) {
Logger.getLogger(PrintApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
});

} catch (Exception ex) {
ex.printStackTrace();
}
}

// TODO overwrite start(), stop() and destroy() methods
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == printButton) {
print(“11401.pdf”);
}
} catch (Exception e1) {
System.out.println(“error : ” + e1.toString());
e1.printStackTrace();
}
}

public void doPrint(String filename) {
if (method.equals(“JPedal”)) {
printWithJPedal(filename);
} else if (method.equals(“pdfp”)) {
generate();
print(filename);
}

}

public void printWithJPedal(String filename) {
try {
final String path = muatTurunKeLocal(filename);
if (path != null) {
String r = (String) AccessController.doPrivileged(
new PrivilegedAction() {

public Object run() {
try {
log.log(Level.OFF, path);
pjob = PrinterJob.getPrinterJob();
if (pjob.printDialog()) {
new PrintWithJPedal().wc_PrintPDF(path, pjob);
log.log(Level.OFF, “Success”);
return “Success”;
}

return “”;

} catch (Exception ex) {
ex.printStackTrace();
Logger.getLogger(PrintApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
});

System.out.println(“r::” + r);
if (r.equals(“Success”)) {
JOptionPane.showMessageDialog(null, “Cetakan Berjaya”, “eTanah”, JOptionPane.INFORMATION_MESSAGE);
}
delTempFile(path);
}

} catch (Exception ex) {
ex.printStackTrace();
}

}

public void print(String filename) {
try {
final String path = muatTurunKeLocal(filename);
if (path != null) {
final PdfPrint a = new PdfPrint(tmpFolder);
String r = (String) AccessController.doPrivileged(
new PrivilegedAction() {

public Object run() {
try {
return a.executeCmd(path);
} catch (Exception ex) {
Logger.getLogger(PrintApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
});
System.out.println(“r::” + r);
if (r.equals(“Success”)) {
JOptionPane.showMessageDialog(null, “Cetakan Berjaya”, “eTanah”, JOptionPane.INFORMATION_MESSAGE);
}
delTempFile(path);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), “Ralat”, JOptionPane.ERROR_MESSAGE);
}
}

private String muatTurunKeLocal(String fn) {
System.out.println(“fn ::” + fn);
String path = null;
StringBuffer buf = new StringBuffer();
String _fn = null;
try {
java.net.URL url = this.getCodeBase();
buf.append(url.getProtocol() + “://”);
buf.append(url.getHost() + “:” + url.getPort());
buf.append(this.uploadAction);
buf.append(“?filename=” + fn);
System.out.println(“Muat naik ke: ” + buf.toString());
MultipartPostMethod filePost = new MultipartPostMethod(buf.toString());

HttpState initialState = new HttpState();
initialState.addCookies(cookies);
// RFC 2101 cookie management spec is used per default
// to parse, validate, format & match cookies
initialState.setCookiePolicy(CookiePolicy.RFC2109);
HttpClient client = new HttpClient();

client.setConnectionTimeout(5000);
client.setState(initialState);
int status = client.executeMethod(filePost);
Logger.getLogger(PrintApplet.class.getName()).log(Level.SEVERE, null, status);

if (status == HttpStatus.SC_OK) {
System.out.println(“OK..”);
final InputStream is = filePost.getResponseBodyAsStream();

path = tmpFolder + (tmpFolder.endsWith(File.separator) ? “” : File.separator);
System.out.println(“saveFile::”);
_fn = (String) AccessController.doPrivileged(
new PrivilegedAction() {

public Object run() {
try {
return util.saveFile(“tmp.pdf”, is);
} catch (Exception ex) {
Logger.getLogger(PrintApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
});

} else {
JOptionPane.showMessageDialog(null, status + ” : Terdapat Masalah Teknikal.”, “Ralat”, JOptionPane.ERROR_MESSAGE);
return null;
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.getMessage(), “Ralat”, JOptionPane.ERROR_MESSAGE);
return null;
}
path = path + _fn;
return path;
}

private void delTempFile(final String path) {
AccessController.doPrivileged(
new PrivilegedAction() {

public Object run() {
File rootDir = new File(path);
if (rootDir.exists()) {
return rootDir.delete();
}
return false;
}
});
}

public void stateChanged(ChangeEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public void mouseClicked(MouseEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public void mousePressed(MouseEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public void mouseReleased(MouseEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public void mouseEntered(MouseEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public void mouseExited(MouseEvent e) {
throw new UnsupportedOperationException(“Not supported yet.”);
}

public static void main(String[] args) {
// create the frame with a title
JFrame frame = new JFrame(“Upload Demo”);
// exit the application when the JFrame is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the applet to the frame
frame.getContentPane().add(new PrintApplet());
// set the size of the frame (applet will be width by height in size)
int height = 800;
int width = 800;
// pack the frame to get correct insets
frame.pack();
Insets fI = frame.getInsets();
frame.setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);

// center the frame on screen
Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((sD.width - width) / 2, (sD.height - height) / 2);
// make the frame visible
frame.setVisible(true);
}

@Override
public String getAppletInfo() {
return “Applet Information”;
}

//Get parameter info
@Override
public String[][] getParameterInfo() {
return null;
}

/**
* Called by the browser or applet viewer to inform this applet that it is
* being reclaimed and that it should destroy any resources that it has
* allocated.
*
*/
@Override
public void destroy() {
}

/**
* Called by the browser or applet viewer to inform this applet that it
* should start its execution.
*
*/
@Override
public void start() {
startSessionMonitorThread();
}

/**
* Called by the browser or applet viewer to inform this applet that it
* should stop its execution.
*
*/
@Override
public void stop() {
stopSessionMonitorThread();
}

private void startSessionMonitorThread() {
}

private void stopSessionMonitorThread() {
}

/**
* This thread is used to keep session alive
*/
class SessionMonitorThread extends Thread {

volatile boolean stopRunning = false;

@Override
public void run() {
while (!stopRunning) {
try {
//sendRequestToBlankPage();
Thread.sleep(1000 * 60 * 3);
} catch (Exception e) {
}
}
}
}
}

No comments: