Dépôt officiel du code source de l'ERP OpenConcerto
Rev 180 | Blame | Compare with Previous | Last modification | View Log | RSS feed
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.awt.Color;
import java.awt.Desktop;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
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 {
convert2PDF(doc, pdfFileToCreate, Collections.emptyList());
}
public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate, final List<PDFAttachment> attachments) throws Exception {
assert (!SwingUtilities.isEventDispatchThread());
System.out.println("SheetUtils convert2PDF " + doc.getLoadedFile().getAbsolutePath() + " -> " + pdfFileToCreate.getAbsolutePath());
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);
// Attachments
final PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
final Map<String, PDComplexFileSpecification> efMap = new HashMap<>();
for (final PDFAttachment att : attachments) {
// first create the file specification, which holds the embedded file
final PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setFile(att.getFileName());
final InputStream is = new ByteArrayInputStream(att.getBytes());
final PDEmbeddedFile ef = new PDEmbeddedFile(document, is);
// set some of the attributes of the embedded file
ef.setSubtype(att.getMimetype());
ef.setSize(att.getBytes().length);
ef.setCreationDate(new GregorianCalendar());
fs.setEmbeddedFile(ef);
efMap.put(att.getName(), fs);
}
efTree.setNames(efMap);
// attachments are stored as part of the "names" dictionary in the document catalog
final PDDocumentNameDictionary names = new PDDocumentNameDictionary(document.getDocumentCatalog());
names.setEmbeddedFiles(efTree);
document.getDocumentCatalog().setNames(names);
PdfBoxGraphics2DFontTextDrawer fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
final File dir = new File("Fonts");
if (dir.exists()) {
System.out.println("Using fonts dir : " + dir.getAbsolutePath());
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().toLowerCase().endsWith(".ttf")) {
System.out.println("Registering font : " + f.getAbsolutePath());
fontTextDrawer.registerFont(f);
}
}
} else {
System.out.println("No custom fonts dir found : " + dir.getAbsolutePath());
}
// Configure the renderer
ODTRenderer renderer = new ODTRenderer(doc);
renderer.setIgnoreMargins(false);
renderer.setResizeFactor(100);
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();
final int resizeFactor = (int) Math.ceil(Math.max(widthFactor, heightFactor));
renderer.setResizeFactor(resizeFactor);
// Print pages
for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) {
final 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
final double hMargin = (pageSize.getWidth() - renderer.getPageWidthInPixel()) / 2.0;
g2.translate(hMargin, 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(pdfFileToCreate);
// 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;
}
public static void main(String[] args) throws Exception {
// final OpenDocument doc = new OpenDocument(new File("Documents/Facture_FACT128.ods"));
final OpenDocument doc = new OpenDocument(new File("../ODSViewer/documents/bug_marges_pdf/Devis.ods"));
final File file = new File("out.pdf");
convert2PDF(doc, file);
Desktop.getDesktop().open(file);
}
}