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

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

Introduction

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

Prototype

public PDFMergerUtility() 

Source Link

Document

Instantiate a new PDFMergerUtility.

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();/*from w w  w.j  av a2 s.  c o m*/
}

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/*from  w ww.  j a va  2  s  .  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;
                }/* w w w. j  ava 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:ch.dowa.jassturnier.pdf.PdfGenerator.java

public void exportTemplateWithTableMultiPage(HashMap<String, Table.TableBuilder> tableBuildersMap,
        String fileName) throws IOException {
    String vLogoPath = !ResourceLoader.readProperty("LOGOPATH").isEmpty()
            ? ResourceLoader.readProperty("LOGOPATH")
            : null;/*from w ww  .ja  v a 2  s.c  o m*/
    PDDocument mainDoc = new PDDocument();
    PDFMergerUtility merger = new PDFMergerUtility();
    for (Map.Entry<String, TableBuilder> entry : tableBuildersMap.entrySet()) {
        String title = entry.getKey();
        TableBuilder tableBuilder = entry.getValue();

        final PDDocument documentPage = new PDDocument();
        boolean firstPage = true;
        PDImageXObject image = null;
        float imageStartX = 0F;
        float imageStartY = 0F;
        PDRectangle imgSize = null;

        TableDrawer drawer = TableDrawer.builder().table(tableBuilder.build()).startX(docContentStartX())
                .startY(docContentStartY()).endY(documentPadding).build();

        if (vLogoPath != null) {
            image = PDImageXObject.createFromFile(vLogoPath, documentPage);
            imgSize = getImageSizePdf(image);
            imageStartX = imgEndX() - imgSize.getWidth();
            imageStartY = imgEndY() - imgSize.getHeight();
        }

        do {
            PDPage page = new PDPage(pageFormat);
            documentPage.addPage(page);
            try (PDPageContentStream contentStream = new PDPageContentStream(documentPage, page)) {
                if (firstPage) {
                    contentStream.beginText();
                    contentStream.setFont(STANDART_FONT_BOLD, 14);
                    contentStream.newLineAtOffset(docTitelStartX(), docTitelStartY());
                    contentStream.showText(title);
                    contentStream.endText();
                    if (image != null) {
                        contentStream.drawImage(image, imageStartX, imageStartY, imgSize.getWidth(),
                                imgSize.getHeight());
                    }
                    drawer.startY(docContentSartFirsPageY());
                    firstPage = false;
                }
                drawer.contentStream(contentStream).draw();
            }
            drawer.startY(docContentStartY());
        } while (!drawer.isFinished());

        merger.appendDocument(mainDoc, documentPage);
    }

    mainDoc.save(fileName);
    mainDoc.close();
}

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   w  w w. j  a  v  a 2  s.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

private static PDFMergerUtility createPDFMergerUtility(List<InputStream> sources,
        ByteArrayOutputStream mergedPDFOutputStream) {
    LOG.info("Initialising PDF merge utility");
    PDFMergerUtility pdfMerger = new PDFMergerUtility();
    pdfMerger.addSources(sources);/*from  ww  w. ja v  a2  s  .c  o  m*/
    pdfMerger.setDestinationStream(mergedPDFOutputStream);
    return pdfMerger;
}

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 a va2s .  co m
}

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

License:Apache License

/**
 * Concatena os pdf em um nico PDF./*from   w  w w  .  j  a v a 2  s  .c om*/
 * @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());
    }/*from  ww w. jav  a  2 s .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:src.controller.DocumentController.java

/**
 * Ajoute un PDF au document spcifi/* w ww .  ja v a 2  s  . c o m*/
 *
 * @param document
 * @param file
 * @throws IOException
 */
public void addPDFToDocument(PDDocument document, File file) throws IOException {
    PDDocument doc = null;
    try {
        if (document != null && file.exists()) {
            doc = PDDocument.load(file);
            if (doc != null) {
                PDFMergerUtility merger = new PDFMergerUtility();
                merger.appendDocument(document, doc);
            }
        }
    } catch (IOException e) {
        System.out.println(e.toString());
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}