pdf.merge.application.BLL.MergeFile.java Source code

Java tutorial

Introduction

Here is the source code for pdf.merge.application.BLL.MergeFile.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pdf.merge.application.BLL;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.awt.Desktop;
import pdf.merge.application.DAL.PropertiesModel;

/**
 *
 * @author Quentin
 */
public class MergeFile {
    private PDFWriter writer = null;
    private PropertiesModel properties = new PropertiesModel();
    private Boolean headerActivated = Boolean.valueOf(properties.getHeaderIsActivated());
    private Boolean footerActivated = Boolean.valueOf(properties.getFooterIsActivated());
    private String pathToRecordFile = properties.getFilePath();

    public void mergeFiles(String absolutePath, String givenName, File[] fileList)
            throws FileNotFoundException, IOException {
        PDFMergerUtility PDFmerger = new PDFMergerUtility();
        // on ajoute tous els fichiers trouvs
        for (int i = 0; i < fileList.length; i++) {
            PDFmerger.addSource(absolutePath + "\\" + fileList[i].getName());
        }

        // si l'utilisateur n'a pas ajout l'extension en saisisant le nom
        if (!givenName.endsWith(".pdf")) {
            givenName += ".pdf";
        }

        // on cre le nouveau path pour la cration du fichier
        String newFilePath = pathToRecordFile + "/" + givenName;
        PDFmerger.setDestinationFileName(newFilePath);
        // on fusionne les fichiers PDF
        PDFmerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

        // on vrifie si les options pour crire sur le PDF ont t coches
        if (headerActivated || footerActivated) {
            // on instancie le writer
            writer = new PDFWriter(new File(newFilePath), newFilePath, headerActivated, footerActivated,
                    properties.getHeaderContent(), properties.getFooterContent());
        }

        // mthode d'ouverture du fichier fusionn
        loadFile(newFilePath);
    }

    public void loadFile(String lastPDFCreated) throws IOException {
        // on vrifie si le PC peut ouvrir le fichier
        if (Desktop.isDesktopSupported()) {
            final Desktop desktop = Desktop.getDesktop();
            try {
                // on ouvre le fichier cr avec Adobe Reader
                Desktop.getDesktop().open(new File(lastPDFCreated));
            } catch (Exception e) {
                System.out.println("Impossible d'ouvrir le fichier avec l'erreur : " + e);
            }
        }
    }
}