Example usage for org.apache.pdfbox.multipdf PDFMergerUtility setDestinationFileName

List of usage examples for org.apache.pdfbox.multipdf PDFMergerUtility setDestinationFileName

Introduction

In this page you can find the example usage for org.apache.pdfbox.multipdf PDFMergerUtility setDestinationFileName.

Prototype

public void setDestinationFileName(String destination) 

Source Link

Document

Set the name of the destination file.

Usage

From source file:NewClass.java

public static void main(String[] args) throws Exception {
    PDFMergerUtility ut = new PDFMergerUtility();
    ut.addSource("one.pdf");
    ut.addSource("two.pdf");

    ut.setDestinationFileName("result.pdf");
    ut.mergeDocuments();/*www .  j  a  v a  2 s .com*/
}

From source file:ca.uqac.lif.labpal.FileHelper.java

License:Open Source License

/**
 * Merges multiple PDF files into a single file
 * @param dest The destination filename/*  w ww.ja  va 2s .c  o  m*/
 * @param paths The input files
 * @return The array of bytes containing the merged PDF
 */
@SuppressWarnings("deprecation")
public static byte[] mergePdf(String dest, String... paths) {
    try {
        ByteArrayOutputStream out = null;
        List<File> lst = new ArrayList<File>();
        List<PDDocument> lstPDD = new ArrayList<PDDocument>();
        for (String path : paths) {
            File file1 = new File(path);

            lstPDD.add(PDDocument.load(file1));
            lst.add(file1);
        }
        PDFMergerUtility PDFmerger = new PDFMergerUtility();

        // Setting the destination file
        PDFmerger.setDestinationFileName(dest);
        for (File file : lst) {
            // adding the source files
            PDFmerger.addSource(file);

        }
        // Merging the two documents
        PDFmerger.mergeDocuments();

        for (PDDocument pdd : lstPDD) {
            pdd.close();
        }

        PDDocument pdf = PDDocument.load(new File(dest));

        out = new ByteArrayOutputStream();

        pdf.save(out);
        byte[] data = out.toByteArray();
        pdf.close();
        return data;
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage());
    }
    return null;
}

From source file:cdiscisa.StreamUtil.java

private static void mergeFiles(Map<String, String> dosc, ArrayList<Participante> listaParticipantes,
            ArrayList<Directorio> listaDirectorio, String registroPDF, String lista_auto_pdf)
            throws FileNotFoundException, IOException {

        ArrayList<Directorio> listaDirecciones = new ArrayList<>();

        ListIterator<Participante> itParticipantes = listaParticipantes.listIterator();
        ListIterator<Directorio> itDirectorio;

        while (itParticipantes.hasNext()) {
            Participante p = itParticipantes.next();
            itDirectorio = listaDirectorio.listIterator();
            while (itDirectorio.hasNext()) {
                Directorio d = itDirectorio.next();

                if (p.determinante.equalsIgnoreCase(d.determinante) && !listaDirecciones.contains(d)) {
                    listaDirecciones.add(d);
                    break;
                }/*from   www.java 2s  . co m*/
            }
        }

        ListIterator<Directorio> itDireccionesConstancia = listaDirecciones.listIterator();
        while (itDireccionesConstancia.hasNext()) {

            PDFMergerUtility merge = new PDFMergerUtility();

            Directorio d = itDireccionesConstancia.next();
            String x, name;
            name = "";

            SortedSet<String> keys = new TreeSet<String>(dosc.keySet());

            for (String key : keys) {
                String value = dosc.get(key);
                if (value.equalsIgnoreCase(d.determinante)) {

                    if (key.contains("Diplomas_")) {
                        name = key.replaceFirst("Diplomas_", "Capacitacion_");
                    }
                    merge.addSource(new File(key));
                }

            }
            /*
            for (Map.Entry<String, String> entry : dosc.entrySet()) {
            if (entry.getValue().equals(d.determinante)) {
                x = entry.getKey();
                if (x.contains("Diplomas_")){
                    name = x.replaceFirst("Diplomas_", "Capacitacion_");
                }
            merge.addSource(new File(x));
            }
            }
            */

            //InputStream newReg = registroPDF;
            //InputStream newListaAuto = lista_auto_pdf;

            try {
                merge.addSource(new File(lista_auto_pdf));

                if (registroPDF.equalsIgnoreCase("files/RegistroPCJorge Razon2016.pdf")) {
                    merge.addSource(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream(registroPDF));
                } else {
                    merge.addSource(new File(registroPDF));
                }

                merge.setDestinationFileName(name);
                merge.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "registroPDF: " + registroPDF + "\nlista_auto_pdf: "
                        + lista_auto_pdf + "\n" + ex.getMessage());
            }

            //newReg = null;
            //newListaAuto = null;
            merge = null;

        }

        //"Capacitacion_BAE_Centro de Huinala_2631_MULTI_19ago2015"

        //Capacitacin + formato tienda + nombre sucursal + numero sucursal + nombre curso + ddmmaaaa

        // Save the results and ensure that the document is properly closed:
        //document.save(savePath + File.separator + "Certificado_" + d.formato + "_" + d.unidad + "_" + d.determinante + "_MULTI_" + formatedDate + ".pdf");

    }

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry//  w w w  . j  av  a2 s .  co  m
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:pdf.merge.application.BLL.MergeFile.java

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());
    }//  w  ww  .jav a2  s  .com

    // 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);
}