package net.sourceforge.phpeclipse.wiki.export.pdf; import java.awt.Color; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.IOverwriteQuery; import com.lowagie.text.Chapter; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; //import de.java2html.converter.JavaSource2HTMLConverter; //import de.java2html.javasource.JavaSource; //import de.java2html.javasource.JavaSourceParser; //import de.java2html.options.Java2HtmlConversionOptions; public final class WikiPDFExporter implements IRunnableWithProgress { //The constants for the overwrite 3 state private static final int OVERWRITE_NOT_SET = 0; private static final int OVERWRITE_NONE = 1; private static final int OVERWRITE_ALL = 2; private int overwriteState = OVERWRITE_NOT_SET; private List errorTable = new ArrayList(1); private List fResourcesToExport; private IPath fPath; private IOverwriteQuery fOverwriteCallback; public WikiPDFExporter(List resources, String destinationPath, IOverwriteQuery overwriteImplementor) { super(); fResourcesToExport = resources; fPath = new Path(destinationPath); fOverwriteCallback = overwriteImplementor; } // public void export(IContainer folder, String exportDirectoryName, String srcBasePath, IProgressMonitor monitor) throws // IOException, CoreException, // InstantiationException, IllegalAccessException, ClassNotFoundException { // // exportDirectory = new File(exportDirectoryName); // IResource[] resources = folder.members(IResource.FILE); // String templateFileName = Util.getExportTemplate(folder); //// monitor.beginTask(WikiEditorPlugin.getResourceString("Export.wikiPages"), resources.length + 1); // for (int i = 0; i < resources.length; i++) { // if (resources[i] instanceof IFile) { // monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile")+resources[i].getLocation()); // CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath); // monitor.worked(1); // } else if (resources[i] instanceof IFolder) { // monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFolder")+resources[i].getLocation()); // export((IFolder) resources[i], exportDirectoryName, srcBasePath, monitor); // monitor.worked(1); // } // } // // monitor.subTask(WikiEditorPlugin.getResourceString("Export.linkedResources")); // // exportLinkedResources(); // // createIndex(); //// monitor.worked(1); // } /** * TODO: This is a horrible hack for a quick solution. */ // private void createIndex() throws IOException { // File indexFile = createHtmlFile("index"); // // PrintWriter writer = new PrintWriter(new FileWriter(indexFile)); // writer.println(""); // writer.println(""); // writer.println(""); // writer.println(" "); // writer.print(" Index"); // writer.println(" "); // writer.println(" "); // // Iterator iterator = index.iterator(); // while (iterator.hasNext()) { // String name = (String) iterator.next(); // writer.print("
"); // writer.println("" + name + ""); // } // // writer.println(" "); // writer.println(" "); // writer.flush(); // writer.close(); // } // private void exportLinkedResources() throws IOException { // if (!exportLinkMaker.hasLinkedDocuments()) { // return; // } // File workspaceExport = new File(exportDirectory, WikiPDFExporter.WORKSPACE); // if (!workspaceExport.exists()) { // workspaceExport.mkdir(); // } // HashMap map = exportLinkMaker.getLinkedResources(); // Iterator iterator = map.keySet().iterator(); // while (iterator.hasNext()) { // IResource resource = (IResource) iterator.next(); // String location = (String) map.get(resource); // export(resource, location); // } // } // private void export(IResource resource, String location) throws IOException { // File destination = new File(exportDirectory, location); // // if (destination.isDirectory()) { // return; // } // if (!destination.exists()) { // destination.getParentFile().mkdirs(); // } // File source = new File(resource.getLocation().toString()); // if (isJavaResource(resource)) { // javaToHtml(source, new File(destination.getParentFile(), destination.getName())); // } else { // copy(source, destination); // } // } // private boolean isJavaResource(IResource resource) { // return "java".equals(resource.getFileExtension()); // } // private void javaToHtml(File source, File destination) throws IOException { // JavaSource java = new JavaSourceParser().parse(new FileReader(source)); // JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter(java); // Java2HtmlConversionOptions options = Java2HtmlConversionOptions.getDefault(); // options.setShowLineNumbers(true); // options.setShowFileName(true); // options.setShowJava2HtmlLink(true); // converter.setConversionOptions(options); // FileWriter writer = new FileWriter(destination); // converter.convert(writer); // writer.flush(); // writer.close(); // } // private void copy(File source, File dest) throws IOException { // FileChannel in = null; // FileChannel out = null; // try { // in = new FileInputStream(source).getChannel(); // out = new FileOutputStream(dest).getChannel(); // long size = in.size(); // MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); // out.write(buf); // } finally { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // } // } /* * (non-Javadoc) * * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor) */ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { WikiFilesVisitor visitor = new WikiFilesVisitor(); for (int i = 0; i < fResourcesToExport.size(); i++) { try { ((IResource) fResourcesToExport.get(i)).accept(visitor); } catch (CoreException e) { e.printStackTrace(); } } List list = visitor.getList(); Collections.sort(list, new IFileComparator()); IFile file = null; FileOutputStream os = null; String pdffilename = fPath.toString(); Document document = new Document(PageSize.A4); PdfWriter pdfWriter = null; try { os = new FileOutputStream(pdffilename); pdfWriter = PdfWriter.getInstance(document, os); pdfWriter.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.open(); document.resetPageCount(); int chapterNumber = 1; for (int i = 0; i < list.size(); i++) { try { file = (IFile) list.get(i); if (file.exists()) { monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile") + file.getLocation()); StringBuffer htmlBuffer = new StringBuffer(); htmlBuffer.append(""); boolean noContent = CreatePageAction.createFragmentPage(file, htmlBuffer); htmlBuffer.append(""); if (!noContent) { System.out.println(file.getLocation().toString()); System.out.println(htmlBuffer.toString()); String fileName = file.getName(); fileName = fileName.replaceAll("_", " "); int dotIndex = fileName.lastIndexOf('.'); if (dotIndex>0) { fileName = fileName.substring(0,dotIndex); } Paragraph title = new Paragraph(fileName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, Color.BLACK)); Chapter chapter = new Chapter(title, chapterNumber++); document.add(chapter); appendArticle(document, htmlBuffer); } monitor.worked(1); } } catch (Exception e) { String error = "PDF export exception: "+e.getMessage(); if (file!=null) { error = file.getLocation().toString()+" - "+e.getMessage(); } addError(error, e); } } } catch (Exception e) { String error = "PDF export exception: "+e.getMessage(); addError(error, e); } finally { document.close(); if (pdfWriter != null) { pdfWriter.close(); } if (os != null) { try { os.close(); } catch (IOException e1) { } } } System.out.println(fPath.toString()); } /** * @param document * @param htmlBuffer * @param monitor */ private void appendArticle(Document document, StringBuffer htmlBuffer) { StringReader stream = null; try { WPHtmlParser parser = new WPHtmlParser(); stream = new StringReader(htmlBuffer.toString()); parser.go(document, stream); } catch (Exception e) { addError("PDF export exception", e); } finally { if (stream != null) { stream.close(); } } } // public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { // // WikiFilesVisitor visitor = new WikiFilesVisitor(); // for (int i = 0; i < fResourcesToExport.size(); i++) { // try { // ((IResource) fResourcesToExport.get(i)).accept(visitor); // } catch (CoreException e) { // e.printStackTrace(); // } // } // // List list = visitor.getList(); // Collections.sort(list, new IFileComparator()); // IFile file; // // FileOutputStream os = null; // String pdffilename = fPath.toString(); // try { // os = new FileOutputStream(pdffilename); // Document document = new Document(PageSize.A4); // PdfWriter pdfWriter = PdfWriter.getInstance(document, os); // document.open(); // document.resetPageCount(); // for (int i = 0; i < list.size(); i++) { // try { // file = (IFile) list.get(i); // monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile") + file.getLocation()); //// System.out.println(file.getLocation().toString()); // StringBuffer htmlBuffer = new StringBuffer(); // // TODO add the real title here: // htmlBuffer.append("

" + file.getName() + "


"); // boolean noContent = CreatePageAction.createFragmentPage(file, htmlBuffer); // if (i < list.size() - 1) { // // TODO create a boolean flag to determine, if we would like a new page or only horizontal ruler // htmlBuffer.append("
"); // } //// System.out.println(htmlBuffer.toString()); // // if (!noContent) { // appendArticle(document, htmlBuffer); // } // // CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath); // monitor.worked(1); // } catch (Exception e) { // addError("PDF export exception", e); // } // } // document.close(); // } catch (Exception e) { // addError("PDF export exception", e); // } finally { // if (os != null) { // try { // os.close(); // } catch (IOException e1) { // } // } // } // // System.out.println(fPath.toString()); // } // // /** // * @param document // * @param htmlBuffer // * @param monitor // */ // private void appendArticle(Document document, StringBuffer htmlBuffer) { // StringReader stream = null; // try { //// WPHtmlParser parser = new WPHtmlParser(); // stream = new StringReader(htmlBuffer.toString()); //// parser.go(document, stream); // new HTMLWorker(document).parse(stream); // } catch (Exception e) { // addError("PDF export exception", e); // } finally { // if (stream != null) { // stream.close(); // } // } // } /** * Add a new entry to the error table with the passed information */ protected void addError(String message, Throwable e) { e.printStackTrace(); errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, message, e)); } /** * Set this boolean indicating whether exported resources should automatically overwrite existing files when a conflict occurs. If * not query the user. * * @param value * boolean */ public void setOverwriteFiles(boolean value) { if (value) overwriteState = OVERWRITE_ALL; } /** * Returns the status of the export operation. If there were any errors, the result is a status object containing individual * status objects for each error. If there were no errors, the result is a status object with error code OK. * * @return the status */ public IStatus getStatus() { IStatus[] errors = new IStatus[errorTable.size()]; errorTable.toArray(errors); return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, "PDF export problems occured", //$NON-NLS-1$ null); } // test // public static void main(String[] args) { // try { // WPHtmlParser parser = new WPHtmlParser(); // Document document = new Document(); // String htmlfilename = "C:/eclipse/wikibooks/wpbin/Synästhesie.html"; // String pdffilename = "C:/eclipse/wikibooks/wpbin/code_java1.pdf"; // // PdfWriter.getInstance(document, new FileOutputStream(pdffilename)); // parser.go(document, htmlfilename); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (DocumentException e) { // e.printStackTrace(); // } // } }