OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.generationDoc;
15
 
57 ilm 16
import org.openconcerto.erp.preferences.GenerationDocGlobalPreferencePanel;
17
import org.openconcerto.sql.model.DBRoot;
18
import org.openconcerto.sql.preferences.SQLPreferences;
25 ilm 19
import org.openconcerto.utils.ExceptionHandler;
73 ilm 20
import org.openconcerto.utils.FileUtils;
25 ilm 21
 
18 ilm 22
import java.io.File;
23
import java.io.FileOutputStream;
24
import java.io.FilenameFilter;
25
import java.io.IOException;
26
import java.util.ArrayList;
177 ilm 27
import java.util.Calendar;
18 ilm 28
import java.util.Collections;
29
import java.util.Comparator;
30
import java.util.List;
31
 
32
import javax.swing.JOptionPane;
33
import javax.swing.SwingUtilities;
34
 
177 ilm 35
import org.apache.pdfbox.pdmodel.PDDocument;
36
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
37
import org.apache.pdfbox.pdmodel.PDPage;
38
import org.apache.pdfbox.pdmodel.PDPageContentStream;
39
import org.apache.pdfbox.pdmodel.common.PDRectangle;
40
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
41
import org.apache.pdfbox.util.Matrix;
18 ilm 42
import org.jopendocument.model.OpenDocument;
43
import org.jopendocument.renderer.ODTRenderer;
44
 
45
import com.lowagie.text.PageSize;
46
 
177 ilm 47
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D;
48
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawer;
49
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawerDefaultFonts;
50
 
18 ilm 51
public class SheetUtils {
52
 
57 ilm 53
    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest) {
25 ilm 54
        // FIXME: !!!!!!!!
57 ilm 55
        return convertToOldFile(root, fileName, pathDest, fDest, ".ods");
18 ilm 56
    }
57
 
73 ilm 58
    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest, String extension) {
132 ilm 59
        return convertToOldFile(root, fileName, pathDest, fDest, extension, true);
73 ilm 60
    }
61
 
18 ilm 62
    /**
63
     * Déplace le fichier, si il existe, dans le répertoire.
64
     *
65
     * @param fileName nom du fichier sans extension
66
     * @param pathDest
67
     * @param fDest
68
     * @return
69
     */
73 ilm 70
    public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest, String extension, boolean move) {
57 ilm 71
        SQLPreferences prefs = new SQLPreferences(root);
72
        if (prefs.getBoolean(GenerationDocGlobalPreferencePanel.HISTORIQUE, true) && fDest.exists()) {
18 ilm 73
            int i = 0;
74
            String destName = fileName;
75
            File pathOld = new File(pathDest, "Historique");
76
            pathOld.mkdirs();
77
            while (fDest.exists()) {
78
                destName = fileName + "_" + i;
79
                fDest = new File(pathOld, destName + extension);
80
                i++;
81
            }
82
            File fTmp = new File(pathDest, fileName + extension);
83
 
73 ilm 84
            if (move) {
85
                if (!fTmp.renameTo(fDest)) {
86
                    final File finalFile = fDest;
87
                    System.err.println("Unable to rename:" + fTmp.getAbsolutePath());
88
                    System.err.println("To:" + fDest.getAbsolutePath());
89
                    SwingUtilities.invokeLater(new Runnable() {
90
                        public void run() {
91
                            try {
18 ilm 92
 
73 ilm 93
                                JOptionPane.showMessageDialog(null, "Le fichier " + finalFile.getCanonicalPath()
94
                                        + " 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.");
95
                            } catch (IOException e) {
96
                                e.printStackTrace();
97
                            }
18 ilm 98
                        }
73 ilm 99
                    });
100
                    return fTmp;
101
                }
102
            } else {
103
                try {
104
                    FileUtils.copyFile(fTmp, fDest);
105
                } catch (IOException exn) {
106
                    // TODO Bloc catch auto-généré
107
                    ExceptionHandler.handle("Une erreur est survenue lors de la copie du fichier.", exn);
108
                }
18 ilm 109
            }
110
            fDest = new File(pathDest, fileName + extension);
111
        }
112
        return fDest;
113
    }
114
 
25 ilm 115
    public static List<File> getHistorique(final String fileName, File pathDest) {
18 ilm 116
        File pathOld = new File(pathDest, "Historique");
117
        File[] files = pathOld.listFiles(new FilenameFilter() {
118
 
119
            @Override
120
            public boolean accept(File dir, String name) {
121
                return name.startsWith(fileName);
122
 
123
            }
124
        });
125
        List<File> result = new ArrayList<File>();
126
        if (files != null) {
127
            for (int i = 0; i < files.length; i++) {
128
                result.add(files[i]);
129
            }
130
        }
131
        Collections.sort(result, new Comparator<File>() {
132
            @Override
133
            public int compare(File o1, File o2) {
134
                // TODO Auto-generated method stub
135
                return o1.getName().compareTo(o2.getName());
136
            }
137
        });
138
        return result;
139
    }
140
 
25 ilm 141
    public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate) throws Exception {
65 ilm 142
        assert (!SwingUtilities.isEventDispatchThread());
143
        try {
177 ilm 144
            PDDocument document = new PDDocument();
145
            PDDocumentInformation info = new PDDocumentInformation();
146
            info.setCreator("OpenConcerto");
147
            info.setProducer("OpenConcerto");
148
            info.setCreationDate(Calendar.getInstance());
149
            info.setModificationDate(Calendar.getInstance());
150
            document.setDocumentInformation(info);
18 ilm 151
 
65 ilm 152
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFileToCreate);
18 ilm 153
 
177 ilm 154
            PdfBoxGraphics2DFontTextDrawer fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
155
            final File dir = new File("Fonts");
156
            if (dir.exists()) {
157
                fontTextDrawer.registerFontFromDirectory(dir);
158
            }
18 ilm 159
 
65 ilm 160
            // Configure the renderer
161
            ODTRenderer renderer = new ODTRenderer(doc);
162
            renderer.setIgnoreMargins(false);
163
            renderer.setPaintMaxResolution(true);
177 ilm 164
            PDRectangle pageSize = PDRectangle.A4;
18 ilm 165
 
132 ilm 166
            // Scale the renderer to fit width or height
177 ilm 167
            final double widthFactor = renderer.getPrintWidth() / pageSize.getWidth();
168
            final double heightFactor = renderer.getPrintHeight() / pageSize.getHeight();
132 ilm 169
            renderer.setResizeFactor(Math.max(widthFactor, heightFactor));
18 ilm 170
 
65 ilm 171
            // Print pages
172
            for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) {
177 ilm 173
                PDPage page = new PDPage(pageSize);
174
                document.addPage(page);
175
                PdfBoxGraphics2D g2 = new PdfBoxGraphics2D(document, pageSize.getWidth(), pageSize.getHeight());
176
                g2.setFontTextDrawer(fontTextDrawer);
18 ilm 177
 
132 ilm 178
                // centrage horizontal, alignement vertical en haut
179
                g2.translate((PageSize.A4.getWidth() - renderer.getPrintWidthInPixel()) / 2.0, 0);
180
 
65 ilm 181
                // Render
182
                renderer.setCurrentPage(i);
183
                renderer.paintComponent(g2);
184
                g2.dispose();
21 ilm 185
 
177 ilm 186
                final PDFormXObject xform = g2.getXFormObject();
187
                final Matrix matrix = new Matrix();
188
                matrix.translate(0, 0);
189
                final PDPageContentStream contentStream = new PDPageContentStream(document, page);
190
                contentStream.transform(matrix);
191
                contentStream.drawForm(xform);
192
                contentStream.close();
65 ilm 193
            }
177 ilm 194
            document.save(fileOutputStream);
65 ilm 195
            // Close the PDF document
196
            document.close();
21 ilm 197
 
65 ilm 198
        } catch (Exception originalExn) {
199
            ExceptionHandler.handle("Impossible de créer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn);
200
        }
19 ilm 201
 
18 ilm 202
    }
25 ilm 203
 
204
    /**
205
     * Get a new file with an other extension
206
     *
207
     * @param the file (ex: Test.ods)
208
     * @param the extension (ex: pdf)
132 ilm 209
     */
25 ilm 210
    static File getFileWithExtension(File file, String extension) {
211
        if (!extension.startsWith(".")) {
212
            extension = "." + extension;
213
        }
214
        String name = file.getName();
215
        int i = name.lastIndexOf(".");
216
        name = name.substring(0, i) + extension;
217
        final File f = new File(file.getParent(), name);
218
        return f;
219
    }
18 ilm 220
}