OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 132 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.generationDoc;

import org.openconcerto.erp.preferences.GenerationDocGlobalPreferencePanel;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.util.Matrix;
import org.jopendocument.model.OpenDocument;
import org.jopendocument.renderer.ODTRenderer;

import com.lowagie.text.PageSize;

import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D;
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawer;
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawerDefaultFonts;

public class SheetUtils {

    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest) {
        // FIXME: !!!!!!!!
        return convertToOldFile(root, fileName, pathDest, fDest, ".ods");
    }

    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest, String extension) {
        return convertToOldFile(root, fileName, pathDest, fDest, extension, true);
    }

    /**
     * Déplace le fichier, si il existe, dans le répertoire.
     * 
     * @param fileName nom du fichier sans extension
     * @param pathDest
     * @param fDest
     * @return
     */
    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest, String extension, boolean move) {
        SQLPreferences prefs = new SQLPreferences(root);
        if (prefs.getBoolean(GenerationDocGlobalPreferencePanel.HISTORIQUE, true) && fDest.exists()) {
            int i = 0;
            String destName = fileName;
            File pathOld = new File(pathDest, "Historique");
            pathOld.mkdirs();
            while (fDest.exists()) {
                destName = fileName + "_" + i;
                fDest = new File(pathOld, destName + extension);
                i++;
            }
            File fTmp = new File(pathDest, fileName + extension);

            if (move) {
                if (!fTmp.renameTo(fDest)) {
                    final File finalFile = fDest;
                    System.err.println("Unable to rename:" + fTmp.getAbsolutePath());
                    System.err.println("To:" + fDest.getAbsolutePath());
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            try {

                                JOptionPane.showMessageDialog(null, "Le fichier " + finalFile.getCanonicalPath()
                                        + " n'a pu être créé. \n Impossible de déplacer le fichier existant dans l'historique.\n Vérifier que le document n'est pas déjà ouvert.");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    return fTmp;
                }
            } else {
                try {
                    FileUtils.copyFile(fTmp, fDest);
                } catch (IOException exn) {
                    // TODO Bloc catch auto-généré
                    ExceptionHandler.handle("Une erreur est survenue lors de la copie du fichier.", exn);
                }
            }
            fDest = new File(pathDest, fileName + extension);
        }
        return fDest;
    }

    public static List<File> getHistorique(final String fileName, File pathDest) {
        File pathOld = new File(pathDest, "Historique");
        File[] files = pathOld.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith(fileName);

            }
        });
        List<File> result = new ArrayList<File>();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                result.add(files[i]);
            }
        }
        Collections.sort(result, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                // TODO Auto-generated method stub
                return o1.getName().compareTo(o2.getName());
            }
        });
        return result;
    }

    public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate) throws Exception {
        assert (!SwingUtilities.isEventDispatchThread());
        try {
            PDDocument document = new PDDocument();
            PDDocumentInformation info = new PDDocumentInformation();
            info.setCreator("OpenConcerto");
            info.setProducer("OpenConcerto");
            info.setCreationDate(Calendar.getInstance());
            info.setModificationDate(Calendar.getInstance());
            document.setDocumentInformation(info);

            FileOutputStream fileOutputStream = new FileOutputStream(pdfFileToCreate);

            PdfBoxGraphics2DFontTextDrawer fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
            final File dir = new File("Fonts");
            if (dir.exists()) {
                fontTextDrawer.registerFontFromDirectory(dir);
            }

            // Configure the renderer
            ODTRenderer renderer = new ODTRenderer(doc);
            renderer.setIgnoreMargins(false);
            renderer.setPaintMaxResolution(true);
            PDRectangle pageSize = PDRectangle.A4;

            // Scale the renderer to fit width or height
            final double widthFactor = renderer.getPrintWidth() / pageSize.getWidth();
            final double heightFactor = renderer.getPrintHeight() / pageSize.getHeight();
            renderer.setResizeFactor(Math.max(widthFactor, heightFactor));

            // Print pages
            for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) {
                PDPage page = new PDPage(pageSize);
                document.addPage(page);
                PdfBoxGraphics2D g2 = new PdfBoxGraphics2D(document, pageSize.getWidth(), pageSize.getHeight());
                g2.setFontTextDrawer(fontTextDrawer);

                // centrage horizontal, alignement vertical en haut
                g2.translate((PageSize.A4.getWidth() - renderer.getPrintWidthInPixel()) / 2.0, 0);

                // Render
                renderer.setCurrentPage(i);
                renderer.paintComponent(g2);
                g2.dispose();

                final PDFormXObject xform = g2.getXFormObject();
                final Matrix matrix = new Matrix();
                matrix.translate(0, 0);
                final PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.transform(matrix);
                contentStream.drawForm(xform);
                contentStream.close();
            }
            document.save(fileOutputStream);
            // Close the PDF document
            document.close();

        } catch (Exception originalExn) {
            ExceptionHandler.handle("Impossible de créer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn);
        }

    }

    /**
     * Get a new file with an other extension
     * 
     * @param the file (ex: Test.ods)
     * @param the extension (ex: pdf)
     */
    static File getFileWithExtension(File file, String extension) {
        if (!extension.startsWith(".")) {
            extension = "." + extension;
        }
        String name = file.getName();
        int i = name.lastIndexOf(".");
        name = name.substring(0, i) + extension;
        final File f = new File(file.getParent(), name);
        return f;
    }
}