View Javadoc

1   /***
2    * 
3    */
4   package org.telscenter.pas.ui.pdf.actions;
5   
6   import java.awt.Component;
7   import java.awt.event.ActionEvent;
8   import java.awt.event.ActionListener;
9   import java.beans.PropertyChangeEvent;
10  import java.beans.PropertyChangeListener;
11  import java.io.File;
12  import java.io.FileOutputStream;
13  import java.io.IOException;
14  import java.util.Collection;
15  import java.util.Iterator;
16  import java.util.logging.Logger;
17  
18  import javax.swing.AbstractAction;
19  import javax.swing.Icon;
20  import javax.swing.ImageIcon;
21  import javax.swing.JButton;
22  import javax.swing.JFileChooser;
23  import javax.swing.JPanel;
24  import javax.swing.JTextField;
25  import javax.swing.SwingUtilities;
26  
27  import net.sf.sail.core.entity.User;
28  
29  import org.apache.commons.lang.StringUtils;
30  import org.apache.commons.lang.WordUtils;
31  import org.telscenter.pas.beans.IWorkReporter;
32  import org.telscenter.pas.beans.PasActivity;
33  import org.telscenter.pas.beans.PasProject;
34  import org.telscenter.pas.beans.PasStep;
35  import org.telscenter.pas.common.ui.CommonUI;
36  import org.telscenter.pas.steps.ProjectInfoStep;
37  import org.telscenter.pas.steps.ShowAllWorkStep;
38  import org.telscenter.pas.ui.dialog.PasDialogHelper;
39  import org.telscenter.pas.ui.pdf.PDFFileFilter;
40  import org.telscenter.pas.ui.pdf.PDFUtil;
41  import org.telscenter.pas.ui.util.ComponentUtil;
42  
43  import com.lowagie.text.Chunk;
44  import com.lowagie.text.Document;
45  import com.lowagie.text.DocumentException;
46  import com.lowagie.text.Paragraph;
47  import com.lowagie.text.Rectangle;
48  import com.lowagie.text.pdf.BaseFont;
49  import com.lowagie.text.pdf.PdfContentByte;
50  import com.lowagie.text.pdf.PdfPCell;
51  import com.lowagie.text.pdf.PdfPTable;
52  import com.lowagie.text.pdf.PdfPageEvent;
53  import com.lowagie.text.pdf.PdfTemplate;
54  import com.lowagie.text.pdf.PdfWriter;
55  
56  /***
57   * @author anthonyperritano
58   * 
59   */
60  public class GeneratePDFAction extends AbstractAction implements PdfPageEvent {
61  	/***
62  	 * Logger for this class
63  	 */
64  	private static final Logger logger = Logger
65  			.getLogger(GeneratePDFAction.class.getName());
66  
67  	private PasProject pasProject = null;
68  
69  	private Document document;
70  
71  	private PdfTemplate tpl;
72  
73  	private BaseFont helv;
74  
75  	private JTextField saveTextField;
76  
77  	private JFileChooser chooser;
78  
79  	private JButton changeFileNameButton;
80  
81  	private String generatedFileName;
82  
83  	public GeneratePDFAction(PasProject pasProject) {
84  		super();
85  		this.pasProject = pasProject;
86  	}
87  
88  	/***
89  	 * @param name
90  	 */
91  	public GeneratePDFAction(String name) {
92  		super(name);
93  		// TODO Auto-generated constructor stub
94  	}
95  
96  	public GeneratePDFAction(ImageIcon icon, String title, PasProject pasProject) {
97  		super(title, icon);
98  		this.pasProject = pasProject;
99  	}
100 
101 	public GeneratePDFAction(String name, Icon icon) {
102 		super(name, icon);
103 		// TODO Auto-generated constructor stub
104 	}
105 
106 	
107 	/***
108 	 * @param object
109 	 * @param pasProject2
110 	 */
111 	public GeneratePDFAction(Object object, PasProject pasProject) {
112 		// TODO Auto-generated constructor stub
113 	}
114 
115 	public void runAction() {
116 		SwingUtilities.invokeLater(new Runnable() {
117 			public void run() {
118 				openSaveDialog();
119 			}
120 		});
121 	}
122 	
123 	public void actionPerformed(ActionEvent e) {
124 		this.runAction();
125 	}
126 
127 	protected boolean generatePDF() {
128 
129 		boolean isSuccessful = true;
130 		try {
131 			// Create Heading
132 			document.add(PDFUtil.createHeading(this.getUserNamesCommaSep(),
133 					pasProject.getTitle()));
134 			document.add(Chunk.NEWLINE);
135 			PdfPTable docTable = new PdfPTable(1);
136 
137 			// make the length of the page
138 			docTable.setWidthPercentage(100.0f);
139 
140 			PasActivity[] activities = pasProject.getActivities();
141 			for (int i = 0; i < activities.length; i++) {
142 				PasActivity activity = activities[i];
143 
144 				PasStep[] steps = activity.getSteps();
145 				
146 				if (steps.length > 0) {
147 					docTable.addCell(PDFUtil.createActivityTitle(" Activity "
148 							+ (i + 1) + ": " + activity.getTitle()));
149 					for (int j = 0; j < steps.length; j++) {
150 						PasStep step = steps[j];
151 						if (step instanceof IWorkReporter) {
152 							IWorkReporter reporter = (IWorkReporter) step;
153 							PdfPCell reportForLearner = reporter
154 									.getReportForLearnerPDF(pasProject.getAnnotationService());
155 							
156 							
157 							if (reportForLearner != null) {
158 								docTable.addCell(reportForLearner);
159 							} 
160 						}// if
161 					}// for
162 
163 					docTable.addCell(PDFUtil.createEmptyCell());
164 					docTable.addCell(PDFUtil.createEmptyCell());
165 
166 				}// if
167 			}// for
168 
169 			document.add(docTable);
170 
171 		} catch (DocumentException e) {
172 			logger.severe("exception: " + e); //$NON-NLS-1$
173 			isSuccessful = false;
174 		}
175 
176 		cleanup();
177 		return isSuccessful;
178 	}
179 
180 	/***
181 	 * @return
182 	 */
183 	protected String getUserNamesCommaSep() {
184 		Collection<User> users = pasProject.getProjectFrame().getUsers();
185 		StringBuffer userNames = new StringBuffer();
186 		for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
187 			User user = iter.next();
188 			userNames.append(user.getDisplayName());
189 			if (iter.hasNext()) {
190 				userNames.append(", ");
191 			}// if
192 		}// for
193 		return userNames.toString();
194 	}
195 
196 	protected void cleanup() {
197 		if (document == null)
198 			return;
199 
200 		document.close();
201 	}
202 
203 	protected void openSaveDialog() {
204 
205 		chooser = new JFileChooser();
206 		chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
207 		chooser.setDialogType(JFileChooser.SAVE_DIALOG);
208 		chooser.setMultiSelectionEnabled(true);
209 		chooser.setFileHidingEnabled(true);
210 		chooser.setFileFilter(new PDFFileFilter());
211 		// Show save dialog; this method does not return until the dialog is
212 		// closed
213 		File curDir = chooser.getCurrentDirectory();
214 		chooser.setDialogTitle("" + curDir.getAbsolutePath());
215 
216 		
217 		
218 		saveTextField = null;
219 		Component[] components = chooser.getComponents();
220 		for (int i = 0; i < components.length; i++) {
221 			Component component = components[i];
222 			saveTextField = (JTextField) ComponentUtil.findComponent(component,
223 					JTextField.class);
224 			if (saveTextField != null)
225 				break;
226 		}
227 
228 		JPanel parent = (JPanel) saveTextField.getParent();
229 		changeFileNameButton = new JButton("Generate File Name");
230 		changeFileNameButton.addActionListener(new ActionListener() {
231 		
232 			public void actionPerformed(ActionEvent e) {
233 				saveTextField.setText(generatedFileName);
234 				File file = new File(chooser.getCurrentDirectory().getAbsolutePath() + File.separator + generatedFileName);
235 				chooser.setSelectedFile(file);
236 				//chooser.updateUI();
237 			}});
238 		changeFileNameButton = CommonUI.makeEnhancedButton(changeFileNameButton);
239 		parent.add(changeFileNameButton);
240 		
241 		generatedFileName = generateFileName();
242 		saveTextField.setText(generatedFileName);
243 		// Add listener on chooser to detect changes to current directory
244 		chooser.addPropertyChangeListener(new PropertyChangeListener() {
245 			public void propertyChange(PropertyChangeEvent evt) {
246 				if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt
247 						.getPropertyName())) {
248 					File curDir = chooser.getCurrentDirectory();				    
249 	                	chooser.setDialogTitle(""+curDir.getAbsolutePath());
250 				}
251 			}
252 		});
253 
254 		// Add listener for approve and cancel events
255 		chooser.addActionListener(new AbstractAction() {
256 			public void actionPerformed(ActionEvent evt) {
257 				JFileChooser chooser = (JFileChooser) evt.getSource();
258 
259 				if (JFileChooser.APPROVE_SELECTION.equals(evt
260 						.getActionCommand())) {
261 					// TODO: check for corrent extension
262 
263 					File selectedFile = chooser.getSelectedFile();
264 					String fileName = selectedFile.getName();
265 
266 					boolean isCorrectFormat = StringUtils.contains(fileName,
267 							".pdf");
268 
269 					if (!isCorrectFormat) {
270 						fileName = selectedFile.getAbsolutePath() + ".pdf";
271 					}
272 					boolean isSuccessful = doPDF(fileName);
273 					if(isSuccessful) {
274 						PasDialogHelper.showMessageDialog("Your project work report has successfully been generated",pasProject.getProjectFrame());
275 					} else {
276 						PasDialogHelper.showErrorDialog("There was a problem generating your work report", pasProject.getProjectFrame());
277 					}// if
278 				} else if (JFileChooser.CANCEL_SELECTION.equals(evt
279 						.getActionCommand())) {
280 					// Hide dialog
281 					chooser.setVisible(false);
282 				}
283 			}
284 		});
285 		chooser.showSaveDialog(null);
286 	}
287 
288 	public boolean doPDF(String filePath) {
289 		initPDF(filePath);
290 		return generatePDF();
291 	}
292 
293 	public String generateFileName() {
294 		Collection<User> users = pasProject.getProjectFrame().getUsers();
295 
296 		if (users == null) {
297 			return "ERROR-nosession";
298 		}
299 		
300 		StringBuffer fileName = new StringBuffer();
301 		for (User user : users) {
302 			fileName.append(WordUtils.capitalize(user.getDisplayName()));
303 		}
304 		fileName.append(PDFUtil.getNonSlashDate());
305 		String newFileName = StringUtils.deleteWhitespace(fileName.toString());
306 		return newFileName;
307 	}
308 
309 	protected void initPDF(String filePath) {
310 		if (filePath == null)
311 			return;
312 
313 		document = new Document();
314 		try {
315 
316 			// we create a writer that listens to the document
317 			// and directs a COMMANDS_PROMPTEXPORTWORK-stream to a file
318 			PdfWriter writer = PdfWriter.getInstance(document,
319 					new FileOutputStream(filePath));
320 
321 			// step 3: we add some metadata open the document
322 			writer.setPageEvent(this);
323 			helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
324 			initMetadata();
325 		} catch (DocumentException de) {
326 			logger.severe(de.getMessage() + " -  : exception: " + de); //$NON-NLS-1$
327 		} catch (IOException ioe) {
328 			logger.severe(ioe.getMessage() + " -  : exception: " + ioe); //$NON-NLS-1$
329 		}
330 	}
331 
332 	protected void initMetadata() {
333 		String userNames = getUserNamesCommaSep();
334 		document.addTitle("Work report for " + userNames );
335 		document.addSubject("This a report generated for "
336 				+ this.getUserNamesCommaSep() + " on " + PDFUtil.getSlashDate()
337 				+ " for the project \"" + pasProject.getTitle() + "\" ");
338 		document
339 				.addKeywords(pasProject.getTitle() + ", " + "work report" + ", "
340 						+ userNames);
341 		document.addCreator("TELS COMMANDS_PROMPTEXPORTWORK Generation System");
342 		document.addAuthor(userNames);
343 		document.open();
344 	}
345 
346 	/*
347 	 * (non-Javadoc)
348 	 * 
349 	 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
350 	 *      com.lowagie.text.Document)
351 	 */
352 	public void onEndPage(PdfWriter writer, Document document) {
353 		tpl = writer.getDirectContent().createTemplate(100, 100);
354 		tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100));
355 
356 		PdfContentByte cb = writer.getDirectContent();
357 		String text = "Page " + writer.getPageNumber() + " of ";
358 
359 		float textSize = helv.getWidthPoint(text, 12);
360 		float textBase = document.bottom() - 20;
361 
362 		cb.addTemplate(tpl, document.left() + textSize, textBase);
363 		cb.saveState();
364 
365 	}
366 
367 	/*
368 	 * (non-Javadoc)
369 	 * 
370 	 * @see com.lowagie.text.pdf.PdfPageEventHelper#onCloseDocument(com.lowagie.text.pdf.PdfWriter,
371 	 *      com.lowagie.text.Document)
372 	 */
373 	public void onCloseDocument(PdfWriter writer, Document document) {
374 		tpl.beginText();
375 		tpl.setFontAndSize(helv, 12);
376 		tpl.setTextMatrix(0, 0);
377 		tpl.showText("" + (writer.getPageNumber() - 1));
378 		tpl.endText();
379 
380 	}
381 
382 	/*
383 	 * (non-Javadoc)
384 	 * 
385 	 * @see com.lowagie.text.pdf.PdfPageEvent#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
386 	 *      com.lowagie.text.Document)
387 	 */
388 	public void onOpenDocument(PdfWriter writer, Document document) {
389 		// TODO Auto-generated method stub
390 
391 	}
392 
393 	/*
394 	 * (non-Javadoc)
395 	 * 
396 	 * @see com.lowagie.text.pdf.PdfPageEvent#onStartPage(com.lowagie.text.pdf.PdfWriter,
397 	 *      com.lowagie.text.Document)
398 	 */
399 	public void onStartPage(PdfWriter writer, Document document) {
400 		// TODO Auto-generated method stub
401 
402 	}
403 
404 	/*
405 	 * (non-Javadoc)
406 	 * 
407 	 * @see com.lowagie.text.pdf.PdfPageEvent#onParagraph(com.lowagie.text.pdf.PdfWriter,
408 	 *      com.lowagie.text.Document, float)
409 	 */
410 	public void onParagraph(PdfWriter writer, Document document,
411 			float paragraphPosition) {
412 		// TODO Auto-generated method stub
413 
414 	}
415 
416 	/*
417 	 * (non-Javadoc)
418 	 * 
419 	 * @see com.lowagie.text.pdf.PdfPageEvent#onParagraphEnd(com.lowagie.text.pdf.PdfWriter,
420 	 *      com.lowagie.text.Document, float)
421 	 */
422 	public void onParagraphEnd(PdfWriter writer, Document document,
423 			float paragraphPosition) {
424 		// TODO Auto-generated method stub
425 
426 	}
427 
428 	/*
429 	 * (non-Javadoc)
430 	 * 
431 	 * @see com.lowagie.text.pdf.PdfPageEvent#onChapter(com.lowagie.text.pdf.PdfWriter,
432 	 *      com.lowagie.text.Document, float, com.lowagie.text.Paragraph)
433 	 */
434 	public void onChapter(PdfWriter writer, Document document,
435 			float paragraphPosition, Paragraph title) {
436 		// TODO Auto-generated method stub
437 
438 	}
439 
440 	/*
441 	 * (non-Javadoc)
442 	 * 
443 	 * @see com.lowagie.text.pdf.PdfPageEvent#onChapterEnd(com.lowagie.text.pdf.PdfWriter,
444 	 *      com.lowagie.text.Document, float)
445 	 */
446 	public void onChapterEnd(PdfWriter writer, Document document,
447 			float paragraphPosition) {
448 		// TODO Auto-generated method stub
449 
450 	}
451 
452 	/*
453 	 * (non-Javadoc)
454 	 * 
455 	 * @see com.lowagie.text.pdf.PdfPageEvent#onSection(com.lowagie.text.pdf.PdfWriter,
456 	 *      com.lowagie.text.Document, float, int, com.lowagie.text.Paragraph)
457 	 */
458 	public void onSection(PdfWriter writer, Document document,
459 			float paragraphPosition, int depth, Paragraph title) {
460 		// TODO Auto-generated method stub
461 
462 	}
463 
464 	/*
465 	 * (non-Javadoc)
466 	 * 
467 	 * @see com.lowagie.text.pdf.PdfPageEvent#onSectionEnd(com.lowagie.text.pdf.PdfWriter,
468 	 *      com.lowagie.text.Document, float)
469 	 */
470 	public void onSectionEnd(PdfWriter writer, Document document,
471 			float paragraphPosition) {
472 		// TODO Auto-generated method stub
473 
474 	}
475 
476 	/*
477 	 * (non-Javadoc)
478 	 * 
479 	 * @see com.lowagie.text.pdf.PdfPageEvent#onGenericTag(com.lowagie.text.pdf.PdfWriter,
480 	 *      com.lowagie.text.Document, com.lowagie.text.Rectangle,
481 	 *      java.lang.String)
482 	 */
483 	public void onGenericTag(PdfWriter writer, Document document,
484 			Rectangle rect, String text) {
485 		// TODO Auto-generated method stub
486 
487 	}
488 }