OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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