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 | 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()) {
180 ilm 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());
161
                        fontTextDrawer.registerFont(f);
162
                    }
163
                }
164
 
165
            } else {
166
                System.out.println("No custom fonts dir found : " + dir.getAbsolutePath());
177 ilm 167
            }
18 ilm 168
 
65 ilm 169
            // Configure the renderer
170
            ODTRenderer renderer = new ODTRenderer(doc);
171
            renderer.setIgnoreMargins(false);
172
            renderer.setPaintMaxResolution(true);
177 ilm 173
            PDRectangle pageSize = PDRectangle.A4;
18 ilm 174
 
132 ilm 175
            // Scale the renderer to fit width or height
177 ilm 176
            final double widthFactor = renderer.getPrintWidth() / pageSize.getWidth();
177
            final double heightFactor = renderer.getPrintHeight() / pageSize.getHeight();
132 ilm 178
            renderer.setResizeFactor(Math.max(widthFactor, heightFactor));
18 ilm 179
 
65 ilm 180
            // Print pages
181
            for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) {
177 ilm 182
                PDPage page = new PDPage(pageSize);
183
                document.addPage(page);
184
                PdfBoxGraphics2D g2 = new PdfBoxGraphics2D(document, pageSize.getWidth(), pageSize.getHeight());
185
                g2.setFontTextDrawer(fontTextDrawer);
18 ilm 186
 
132 ilm 187
                // centrage horizontal, alignement vertical en haut
188
                g2.translate((PageSize.A4.getWidth() - renderer.getPrintWidthInPixel()) / 2.0, 0);
189
 
65 ilm 190
                // Render
191
                renderer.setCurrentPage(i);
192
                renderer.paintComponent(g2);
193
                g2.dispose();
21 ilm 194
 
177 ilm 195
                final PDFormXObject xform = g2.getXFormObject();
196
                final Matrix matrix = new Matrix();
197
                matrix.translate(0, 0);
198
                final PDPageContentStream contentStream = new PDPageContentStream(document, page);
199
                contentStream.transform(matrix);
200
                contentStream.drawForm(xform);
201
                contentStream.close();
65 ilm 202
            }
177 ilm 203
            document.save(fileOutputStream);
65 ilm 204
            // Close the PDF document
205
            document.close();
21 ilm 206
 
65 ilm 207
        } catch (Exception originalExn) {
208
            ExceptionHandler.handle("Impossible de créer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn);
209
        }
19 ilm 210
 
18 ilm 211
    }
25 ilm 212
 
213
    /**
214
     * Get a new file with an other extension
215
     *
216
     * @param the file (ex: Test.ods)
217
     * @param the extension (ex: pdf)
132 ilm 218
     */
25 ilm 219
    static File getFileWithExtension(File file, String extension) {
220
        if (!extension.startsWith(".")) {
221
            extension = "." + extension;
222
        }
223
        String name = file.getName();
224
        int i = name.lastIndexOf(".");
225
        name = name.substring(0, i) + extension;
226
        final File f = new File(file.getParent(), name);
227
        return f;
228
    }
18 ilm 229
}