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

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

Introduction

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

Prototype

public void mergeDocuments(MemoryUsageSetting memUsageSetting) throws IOException 

Source Link

Document

Merge the list of source documents, saving the result in the destination file.

Usage

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  w ww .  jav a  2 s .  c  om
            }
        }

        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//from   www .  j av  a2s  . c o 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:io.github.qwefgh90.akka.pdf.PDFUtilWrapper.java

License:Apache License

public static InputStream merge(final List<InputStream> sources, String _title, String _creator,
        String _subject) throws IOException {
    String title = _title == null ? "" : _title;
    String creator = _creator == null ? "" : _creator;
    String subject = _subject == null ? "" : _subject;

    ByteArrayOutputStream mergedPDFOutputStream = null;
    COSStream cosStream = null;/* ww w  .  j av  a2s  .c o  m*/
    try {
        // If you're merging in a servlet, you can modify this example to use the outputStream only
        // as the response as shown here: http://stackoverflow.com/a/36894346/535646
        mergedPDFOutputStream = new ByteArrayOutputStream();
        cosStream = new COSStream();

        PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream);

        // PDF and XMP properties must be identical, otherwise document is not PDF/A compliant
        PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject);
        PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject);
        pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);
        pdfMerger.setDestinationMetadata(xmpMetadata);

        LOG.info("Merging " + sources.size() + " source documents into one PDF");
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        LOG.info("PDF merge successful, size = {" + mergedPDFOutputStream.size() + "} bytes");

        return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray());
    } catch (BadFieldValueException e) {
        throw new IOException("PDF merge problem", e);
    } catch (TransformerException e) {
        throw new IOException("PDF merge problem", e);
    } finally {
        for (InputStream source : sources) {
            IOUtils.closeQuietly(source);
        }
        IOUtils.closeQuietly(cosStream);
        IOUtils.closeQuietly(mergedPDFOutputStream);
    }
}

From source file:org.egov.infra.utils.PdfUtils.java

License:Open Source License

public static byte[] appendFiles(List<InputStream> pdfStreams) {
    try (ByteArrayOutputStream destination = new ByteArrayOutputStream()) {
        PDFMergerUtility pdfMerger = new PDFMergerUtility();
        pdfMerger.setDestinationStream(destination);
        pdfStreams.forEach(pdfMerger::addSource);
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return destination.toByteArray();
    } catch (IOException e) {
        throw new ApplicationRuntimeException("Error occurred while merging pdf files", e);
    }/*from  w  w w .j ava  2  s  .c  o  m*/
}

From source file:org.opensingular.lib.commons.pdf.PDFUtil.java

License:Apache License

/**
 * Concatena os pdf em um nico PDF./* w  ww .  ja v a2  s  .c  o  m*/
 * @param pdfs
 * @return O arquivo retornado  temporrio e deve ser apagado pelo solicitante para no deixa lixo.
 */
@Nonnull
public File merge(@Nonnull List<InputStream> pdfs) throws SingularPDFException {
    try (TempFileProvider tmp = TempFileProvider.createForUseInTryClause(this)) {
        PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
        pdfs.forEach(pdfMergerUtility::addSource);

        File tempMergedFile = tmp.createTempFileByDontPutOnDeleteList("merge.pdf");

        try (FileOutputStream output = new FileOutputStream(tempMergedFile)) {
            pdfMergerUtility.setDestinationStream(output);
            pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
            return tempMergedFile;
        }
    } catch (Exception e) {
        throw new SingularPDFException("Erro realizando merge de arquivos PDF", e);
    } finally {
        for (InputStream in : pdfs) {
            try {
                in.close();
            } catch (IOException e) {
                getLogger().error("Erro fechando inputStrem", e);
            }
        }
    }
}

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  . j  a  va  2s.co m

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

From source file:us.kagome.pdfbox.PDFMergerExample.java

License:Apache License

/**
 * Creates a compound PDF document from a list of input documents.
 * <p>/* w  w w  . ja  va 2 s. c  om*/
 * The merged document is PDF/A-1b compliant, provided the source documents are as well. It
 * contains document properties title, creator and subject, currently hard-coded.
 *
 * @param sources list of source PDF document streams.
 * @return compound PDF document as a readable input stream.
 * @throws IOException if anything goes wrong during PDF merge.
 */
public InputStream merge(final List<InputStream> sources) throws IOException {
    String title = "My title";
    String creator = "Alexander Kriegisch";
    String subject = "Subject with umlauts ";

    ByteArrayOutputStream mergedPDFOutputStream = null;
    COSStream cosStream = null;
    try {
        // If you're merging in a servlet, you can modify this example to use the outputStream only
        // as the response as shown here: http://stackoverflow.com/a/36894346/535646
        mergedPDFOutputStream = new ByteArrayOutputStream();
        cosStream = new COSStream();

        PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream);

        // PDF and XMP properties must be identical, otherwise document is not PDF/A compliant
        PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject);
        PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject);
        //            pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);
        //            pdfMerger.setDestinationMetadata(xmpMetadata);

        LOG.info("Merging " + sources.size() + " source documents into one PDF");
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        LOG.info("PDF merge successful, size = {" + mergedPDFOutputStream.size() + "} bytes");

        return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray());
    } catch (Exception e) {
        throw new IOException("PDF merge problem", e);
    } finally {
        for (InputStream source : sources) {
            IOUtils.closeQuietly(source);
        }
        IOUtils.closeQuietly(cosStream);
        IOUtils.closeQuietly(mergedPDFOutputStream);
    }
}