View Javadoc

1   package org.eparapher.core.tools;
2   
3   import java.io.BufferedReader;
4   import java.io.File;
5   import java.io.FileNotFoundException;
6   import java.io.FileOutputStream;
7   import java.io.FileReader;
8   import java.io.IOException;
9   import java.net.ConnectException;
10  import java.net.MalformedURLException;
11  import java.util.HashMap;
12  import java.util.Map;
13  
14  import org.apache.log4j.Logger;
15  import org.eparapher.core.EParapherManager;
16  
17  import com.artofsolving.jodconverter.DocumentConverter;
18  import com.artofsolving.jodconverter.DocumentFamily;
19  import com.artofsolving.jodconverter.DocumentFormat;
20  import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
21  import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
22  import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
23  
24  import com.lowagie.text.BadElementException;
25  import com.lowagie.text.Document;
26  import com.lowagie.text.DocumentException;
27  import com.lowagie.text.Image;
28  import com.lowagie.text.PageSize;
29  import com.lowagie.text.Paragraph;
30  import com.lowagie.text.pdf.PdfWriter;
31  
32  
33  public class PDFConverterWrapper {
34  	
35  	private static Logger log = Logger.getLogger(PDFConverterWrapper.class);
36  	
37  	public static final String PDF_TEMP_CONVERTED_FILE = ".temp.pdf";
38  
39  	public static final String[] TXT_EXTENTION = { ".txt", ".log" };
40  	public static final String[] XML_EXTENTION = { ".xml", ".dtd", ".xsl", ".xslt", ".xsl" };
41  	public static final String[] IMG_EXTENTION = { ".bmp", ".gif", ".jpg", ".png", ".tif", ".jpeg", ".tiff", ".ps" };
42  	public static final String[] OFF_EXTENTION = { ".doc", ".rtf", ".xls", ".ppt", ".pps" };
43  	public static final String[] OO_WRITER_EXTENTION = { ".odt", ".sxw", ".ott", ".stw" };
44  	public static final String[] OO_CALC_EXTENTION   = { ".ods", ".ots", ".sxc", ".stc" };
45  	public static final String[] OO_IMP_EXTENTION    = { ".odp", ".otp", ".sxi", ".sti" };
46  	public static final String[] OO_DRAW_EXTENTION   = { ".sxd", ".std", ".odg", ".otg"};
47  	public static final String[] WORD2K7_EXT   = { ".docx",".docm",".dotx",".dotm" };
48  	public static final String[] EXCEL2K7_EXT  = { ".xlsx",".xlsm",".xltx",".xltm",".xlsb",".xlam" };
49  	public static final String[] PPT2K7_EXT    = { ".pptx",".pptm",".ppsx",".ppsx",".potx",".potm",".ppam" };
50  	
51  	public PDFConverterWrapper() {
52  		super();
53  	}
54  	
55  	public String convert(String original_file) throws Exception {
56  		String generated_PDF = null;
57  		if (fileExtentionValidator(original_file, TXT_EXTENTION)
58  		 || fileExtentionValidator(original_file, XML_EXTENTION) )
59  			generated_PDF = TxtToPdf(original_file);
60  		else if ( fileExtentionValidator(original_file, IMG_EXTENTION) )
61  			generated_PDF = ImageToPdf(original_file);
62  		else if (  fileExtentionValidator(original_file, OFF_EXTENTION)
63  				|| fileExtentionValidator(original_file, OO_WRITER_EXTENTION)
64  				|| fileExtentionValidator(original_file, OO_CALC_EXTENTION)
65  				|| fileExtentionValidator(original_file, OO_IMP_EXTENTION)
66  				|| fileExtentionValidator(original_file, OO_DRAW_EXTENTION) )
67  			generated_PDF = AnyToPdf(original_file);
68  		else if ( fileExtentionValidator(original_file,  WORD2K7_EXT)
69  				|| fileExtentionValidator(original_file, EXCEL2K7_EXT)
70  				|| fileExtentionValidator(original_file, PPT2K7_EXT) )
71  			throw new Exception("Microsoft Office 2007 Documents convertion not implemented yet in Open Office.\r\n Sorry...");
72  		else throw new Exception("PDF Convertion for " +original_file+ " failed.\r\n This file type is not yet supported in eParapher/Open Office.\r\n Sorry...");
73  		return generated_PDF;
74  	}
75  	
76  	private String ImageToPdf(String original_file) {
77  		
78  		Image img = null;
79  		Document doc = null;
80  		String converted_pdf = getoutputfilename(original_file);
81  		log.info("Generate PDF file " + converted_pdf + " from Image " + original_file);
82  		try {
83  			//Load Image
84  			img = Image.getInstance(original_file);
85  			img.setAlignment(Image.ALIGN_CENTER);
86  			
87  			//Create PDF Doc
88  			doc = new Document();
89  			if (img.getWidth()>img.getHeight()) {
90  				doc.setPageSize( PageSize.A4.rotate() );
91  				log.info("Setting PDF document in landscape.");
92  			} else {
93  				doc.setPageSize( PageSize.A4 );
94  			}
95  			PdfWriter docWriter = PdfWriter.getInstance(doc, new FileOutputStream(converted_pdf));
96  			doc.open();
97  			
98  			float maxWidth  = docWriter.getPageSize().getWidth();
99  			maxWidth = maxWidth - maxWidth/10;
100 			float maxHeigth = docWriter.getPageSize().getHeight();
101 			maxHeigth = maxHeigth - maxHeigth/10;
102 			
103 			//Scale image if it's larger than width and/or Heigth
104 			if ( (img.getScaledWidth() > maxWidth) || (img.getScaledHeight() > maxHeigth) )
105 				img.scaleToFit(maxWidth, maxHeigth);
106 
107 			doc.add(img);
108 		} catch (BadElementException e) {
109 			log.error(""+e.getLocalizedMessage(),e);
110 		} catch (MalformedURLException e) {
111 			log.error(""+e.getLocalizedMessage(),e);
112 		} catch (IOException e) {
113 			log.error(""+e.getLocalizedMessage(),e);
114 		} catch (DocumentException e) {
115 			log.error(""+e.getLocalizedMessage(),e);
116 		}
117 
118 	    doc.close();
119 	    return converted_pdf;
120 	}
121 
122 	private boolean fileExtentionValidator(String mfilename, String[] extentions) {
123 		for (int i = 0; i < extentions.length; i++) {
124 			if (mfilename.toLowerCase().endsWith(extentions[i]))
125 				return true;
126 		}
127 		return false;
128 	}
129 	
130 	public String AnyToPdf(String mfileName) {
131 		
132     	if (!EParapherManager.getInstance().getSettings().isOpenOfficeAutostart())
133 			OODaemonManager.getInstance().start();
134 		
135 		File inputFile = new File(mfileName);
136 		File outputFile = new File(getoutputfilename(mfileName));
137 		log.debug("Create OpenOffice client connexion on localhost:8100");
138 		// connect to an OpenOffice.org instance running on port 8100
139 		OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
140 		//OpenOfficeConnection connection = new PipeOpenOfficeConnection( System.getProperty("user.name") + "_eParapher");
141 		try {
142 			OODaemonManager.getInstance().addOOLibPath();
143 			connection.connect();
144 		} catch (ConnectException e) {
145 			log.error("error while connecting OO: "+e.getLocalizedMessage(),e);
146 			final String eLabel = e.getLocalizedMessage();
147 
148 			return null;
149 		}
150 		
151 		//TODO : Manage More OO PDF Export Options
152 		// see : http://www.artofsolving.com/node/18
153 
154 		// create a PDF DocumentFormat (as normally configured in document-formats.xml)
155 		DocumentFormat customPdfFormat = new DocumentFormat("Portable Document Format", "application/pdf", "pdf");
156 		DocumentFamily df = null;
157 		if ( fileExtentionValidator(mfileName, OO_WRITER_EXTENTION) ) {
158 			df = DocumentFamily.TEXT;
159 			customPdfFormat.setExportFilter(df, "writer_pdf_Export");
160 		}
161 		if ( fileExtentionValidator(mfileName, OO_CALC_EXTENTION) ) {
162 			df = DocumentFamily.SPREADSHEET;
163 			customPdfFormat.setExportFilter(df, "calc_pdf_Export");
164 		}
165 		if ( fileExtentionValidator(mfileName, OO_IMP_EXTENTION ) ) {
166 			df = DocumentFamily.PRESENTATION;
167 			customPdfFormat.setExportFilter(df, "impress_pdf_Export");
168 		}
169 		if ( fileExtentionValidator(mfileName, OO_DRAW_EXTENTION) ) {
170 			df = DocumentFamily.DRAWING;
171 			customPdfFormat.setExportFilter(df, "draw_pdf_Export");
172 		}
173 
174 		// now set our custom options
175 		Map pdfOptions = new HashMap();
176 		//pdfOptions.put("EncryptFile", Boolean.TRUE);
177 		//pdfOptions.put("DocumentOpenPassword", "mysecretpassword");
178 		//0 for PDF1.4 and 1 for PDF/A1
179 		pdfOptions.put("SelectPdfVersion", 1);  
180 		customPdfFormat.setExportOption(df, "FilterData", pdfOptions);
181 
182 		// convert
183 		log.info("Generate PDF file " + outputFile + " from document " + inputFile);
184 		DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
185 		if (df!=null)
186 			converter.convert(inputFile, outputFile, customPdfFormat);
187 		else converter.convert(inputFile, outputFile);
188 		 
189 		// close the connection
190 		log.debug("Disconnect OpenOffice client");
191 		connection.disconnect();
192 		
193 		try {
194 	    	if (!EParapherManager.getInstance().getSettings().isOpenOfficeAutostart())
195 	    		OODaemonManager.getInstance().stop();
196 			return outputFile.getCanonicalPath();
197 		} catch (IOException e) {
198 			String msg = "error in AnyToPdf while stopping OO : " + e.getMessage();
199 			EParapherManager.getInstance().getUI().errorMessage(msg,e);
200 			log.error(msg, e);
201 		}
202 		
203 		return null;
204 	}
205 	private String getoutputfilename(String mfileName) {
206 		String generatedpdffilename = "";
207 		int indexextention = mfileName.lastIndexOf(".");
208 		generatedpdffilename = mfileName.substring(0, indexextention) + PDF_TEMP_CONVERTED_FILE;
209 		return generatedpdffilename;
210 	}
211 
212 	public String TxtToPdf(String mfileName) {
213 	    
214 		Document doc = new Document();
215 		PdfWriter docWriter = null;
216 		String converted_pdf = getoutputfilename(mfileName);
217 		log.info("Generate PDF file " + converted_pdf + " from text document " + mfileName);
218 		
219 		//Init PDF Converter
220 		try {
221 			docWriter = PdfWriter.getInstance(doc, new FileOutputStream(converted_pdf));
222 			doc.open();
223 		} catch (DocumentException e) {
224 			EParapherManager.getInstance().getUI().errorMessage("error in TxtToPdf : " + e.getMessage());
225 			log.error(""+e.getLocalizedMessage(),e);
226 		} catch (FileNotFoundException e) {
227 			EParapherManager.getInstance().getUI().errorMessage("error in TxtToPdf : " + e.getMessage());
228 			log.error(""+e.getLocalizedMessage(),e);
229 		}
230 
231 	    StringBuffer contents = new StringBuffer();
232 	    BufferedReader input = null;
233 	    String line = null;
234 		try {
235 			input = new BufferedReader( new FileReader(mfileName) );
236 		    while (( line = input.readLine()) != null)
237 		    	doc.add(new Paragraph(line + System.getProperty("line.separator")));
238 		} catch (DocumentException e) {
239 
240 			EParapherManager.getInstance().getUI().errorMessage("Error while converting flat text file to PDF : " + e.getMessage(),e);
241 			log.error(""+e.getLocalizedMessage(),e);
242 		} catch (IOException e) {
243 			EParapherManager.getInstance().getUI().errorMessage("Error while converting flat text file to PDF : " + e.getMessage(),e);
244 			log.error(""+e.getLocalizedMessage(),e);
245 		}
246 	    finally {
247 		      try {
248 		        if (input!= null) {
249 		          //flush and close both "input" and its underlying FileReader
250 		          input.close();
251 		        }
252 		      }
253 		      catch (IOException e) {
254 		    	EParapherManager.getInstance().getUI().errorMessage("Error while closing flat text file : " + e.getMessage(),e);
255 		    	log.error(""+e.getLocalizedMessage(),e);
256 		      }
257 		}
258 	    doc.close();
259 	    return converted_pdf;
260 	}
261 
262 	
263 	/**
264 	 * The following method should return a multi-page tiff 
265 	 * @param bai
266 	 * @param imageType
267 	 * @return
268 	public static BufferedImage[] PDFToImage(String file, String imageType) {
269 
270 		BufferedImage[] bi = new BufferedImage[0];
271 		try {
272 			PdfDecoder decoder = new PdfDecoder();
273 			decoder.openPdfFile(file);
274 
275 			 bi = new BufferedImage[decoder.getPageCount()];
276 			for (int i = 0; i < decoder.getPageCount(); i++) {
277 				bi[i] = decoder.getPageAsImage(i);
278 			}
279 		} 
280 		catch (Exception e) 
281 		{
282 			e.printStackTrace();
283 		}
284 		return bi;
285 	}
286 	*/
287 
288 }