Search in sources :

Example 1 with Options

use of fr.opensagres.xdocreport.converter.Options in project vitam-ui by ProgrammeVitam.

the class PdfFileGenerator method createPdfDocument.

/**
 * Method allowing to to generate the dynamic and/or static pdf file.
 * @param xdocGenerator the XDocGenerator used to generate the pdf file.
 * @param dataMap the object containing the data to add to the template.
 * @param pdfOutputStream the generated pdf file /!\ the owner is reponsible for closing the stream.
 * @throws Exception
 */
protected static void createPdfDocument(final IXDocReport xdocGenerator, final Map<String, Object> dataMap, final OutputStream pdfOutputStream) throws Exception {
    final IContext context = xdocGenerator.createContext();
    dataMap.entrySet().forEach(entry -> context.put(entry.getKey(), entry.getValue()));
    final Options options = Options.getFrom(DocumentKind.ODT).to(ConverterTypeTo.PDF);
    xdocGenerator.convert(context, options, pdfOutputStream);
}
Also used : Options(fr.opensagres.xdocreport.converter.Options) IContext(fr.opensagres.xdocreport.template.IContext)

Example 2 with Options

use of fr.opensagres.xdocreport.converter.Options in project Java-Tutorial by gpcodervn.

the class GeneratePDF method main.

public static void main(String[] args) throws XDocConverterException, XDocReportException, IOException {
    // 1) Load Docx file by filling Velocity template engine and cache it to the registry
    InputStream in = new FileInputStream("template/Project.docx");
    IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
    // 2) Create fields metadata to manage lazy loop (#forech velocity) for table row.
    // Create FieldsMetadata by setting Velocity as template engine
    FieldsMetadata fieldsMetadata = report.createFieldsMetadata();
    // Load fields metadata from Java Class
    fieldsMetadata.load("project", Project.class);
    // Load is called with true because model is a list of Developer.
    fieldsMetadata.load("developers", Developer.class, true);
    // 3) Create context Java model
    IContext context = report.createContext();
    Project project = new Project("XDocReport");
    context.put("project", project);
    // Register developers list
    context.put("developers", getDevelopers());
    // 4) Generate report by merging Java model with the Docx
    OutputStream out = new FileOutputStream(new File("Project_Out.pdf"));
    // report.process(context, out);
    Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF);
    report.convert(context, options, out);
}
Also used : Project(com.gpcoder.model.Project) Options(fr.opensagres.xdocreport.converter.Options) IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) FieldsMetadata(fr.opensagres.xdocreport.template.formatter.FieldsMetadata) IContext(fr.opensagres.xdocreport.template.IContext) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 3 with Options

use of fr.opensagres.xdocreport.converter.Options in project javlo by Javlo.

the class DocxUtils method extractContent.

public static List<ComponentBean> extractContent(GlobalContext globalContext, InputStream in, String resourceFolder) throws XDocConverterException, IOException {
    Options options = Options.getFrom(DocumentKind.DOCX).to(ConverterTypeTo.XHTML);
    IConverter converter = ConverterRegistry.getRegistry().getConverter(options);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    converter.convert(in, out, options);
    List<ComponentBean> outContent = new LinkedList<ComponentBean>();
    Document doc = Jsoup.parse(new ByteArrayInputStream(out.toByteArray()), ContentContext.CHARACTER_ENCODING, "/");
    ComponentBean listBean = null;
    for (Element item : doc.select("img,p")) {
        String cssClass = item.attr("class");
        String text = item.text().trim();
        ComponentBean bean = new ComponentBean();
        /* text */
        if (isList(cssClass)) {
            if (listBean == null) {
                listBean = new ComponentBean();
                listBean.setType(DataList.TYPE);
                listBean.setValue("");
            }
            if (listBean.getValue().length() == 0) {
                listBean.setValue(text);
            } else {
                listBean.setValue(listBean.getValue() + "\n" + text);
            }
        } else {
            if (listBean != null) {
                outContent.add(listBean);
                listBean = null;
            }
            if (text.trim().length() > 0 && item.tagName().equals("p")) {
                int titleLevel = getTitleLevel(cssClass);
                if (titleLevel == 0) {
                    bean.setType(WysiwygParagraph.TYPE);
                    bean.setValue(text);
                } else {
                    bean.setType(Heading.TYPE);
                    text = StringEscapeUtils.unescapeXml(StringEscapeUtils.escapeHtml4(text));
                    bean.setValue("text=" + text + "\ndepth=" + titleLevel);
                }
            } else if (item.tagName().equals("img") && item.attr("src") != null && item.attr("src").trim().length() > 0) {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                PrintStream outPrint = new PrintStream(outStream);
                String folder = item.attr("src");
                outPrint.println("dir=" + URLHelper.mergePath(resourceFolder, new File(folder).getParentFile().getPath()));
                outPrint.println("file-name=" + new File(folder).getName());
                outPrint.println(GlobalImage.IMAGE_FILTER + "=full");
                if (item.attr("alt") != null) {
                    outPrint.println("label=" + item.attr("alt"));
                }
                outPrint.close();
                bean.setType(GlobalImage.TYPE);
                bean.setValue(new String(outStream.toByteArray()));
            }
        }
        if (bean.getType() != null && bean.getType().length() > 0) {
            outContent.add(bean);
            bean = new ComponentBean();
        }
    }
    if (listBean != null) {
        outContent.add(listBean);
    }
    return outContent;
}
Also used : ComponentBean(org.javlo.component.core.ComponentBean) Options(fr.opensagres.xdocreport.converter.Options) PrintStream(java.io.PrintStream) Element(org.jsoup.nodes.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) Document(org.jsoup.nodes.Document) LinkedList(java.util.LinkedList) ByteArrayInputStream(java.io.ByteArrayInputStream) IConverter(fr.opensagres.xdocreport.converter.IConverter) File(java.io.File)

Example 4 with Options

use of fr.opensagres.xdocreport.converter.Options in project esup-ecandidat by EsupPortail.

the class CandidatureController method generateDossier.

/**
 * @param  candidature
 * @param  listePresentation
 * @param  listeDatePresentation
 * @param  adresse
 * @param  listePj
 * @param  listeForm
 * @return                       l'InputStream d'export
 * @throws IOException
 * @throws XDocReportException
 */
private ByteArrayInputStream generateDossier(final Candidature candidature, final List<SimpleTablePresentation> listePresentation, final List<SimpleTablePresentation> listeDatePresentation, final List<PjPresentation> listePj, final List<FormulairePresentation> listeForm) throws IOException, XDocReportException {
    InputStream in = null;
    final ByteArrayInOutStream out = new ByteArrayInOutStream();
    try {
        // 1) Load Docx file by filling Velocity template engine and cache
        // it to the registry
        in = MethodUtils.getXDocReportTemplate(ConstanteUtils.TEMPLATE_DOSSIER, i18nController.getLangueCandidat(), cacheController.getLangueDefault().getCodLangue());
        if (in == null) {
            return null;
        }
        /* Chargement des données utiles */
        final Candidat candidat = candidature.getCandidat();
        final CompteMinima cptMin = candidat.getCompteMinima();
        final Formation formation = candidature.getFormation();
        final Commission commission = formation.getCommission();
        /* Utilisation de la demat */
        final Boolean isDematerialisation = isCandidatureDematerialise(candidature);
        /* On place les données dans des bean speciales export */
        final ExportDossierCandidature exportCandidature = new ExportDossierCandidature(campagneController.getLibelleCampagne(cptMin.getCampagne()), commission.getLibComm(), adresseController.getLibelleAdresse(commission.getAdresse(), "\n"), commission.getMailComm(), commission.getTelComm(), formation, MethodUtils.formatToExportHtml(i18nController.getI18nTraduction(commission.getI18nCommentRetourComm())));
        final ExportDossierCandidat exportCandidat = new ExportDossierCandidat(cptMin, candidat, formatterDate.format(candidat.getDatNaissCandidat()), adresseController.getLibelleAdresse(candidat.getAdresse(), "\n"), candidat.getIneCandidat(), candidat.getCleIneCandidat());
        final ExportDossierBac exportDossierBac = new ExportDossierBac(candidat);
        final List<ExportDossierCursusInterne> listeCursusInterne = new ArrayList<>();
        candidat.getCandidatCursusInternes().forEach(e -> listeCursusInterne.add(new ExportDossierCursusInterne(e)));
        listeCursusInterne.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierCursusExterne> listeCursusExterne = new ArrayList<>();
        candidat.getCandidatCursusPostBacs().forEach(e -> listeCursusExterne.add(new ExportDossierCursusExterne(e, tableRefController.getLibelleObtenuCursusByCode(e.getObtenuCursus()))));
        listeCursusExterne.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierStage> listeStage = new ArrayList<>();
        candidat.getCandidatStage().forEach(e -> listeStage.add(new ExportDossierStage(e)));
        listeStage.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierCursusPro> listeCursusPro = new ArrayList<>();
        candidat.getCandidatCursusPros().forEach(e -> listeCursusPro.add(new ExportDossierCursusPro(e)));
        listeCursusPro.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierMotivationAvis> listeMotivationAvis = new ArrayList<>();
        final List<ExportDossierAvis> listeAvis = new ArrayList<>();
        final List<ExportDossierPj> listeExportPj = new ArrayList<>();
        if (!isDematerialisation) {
            listePj.forEach(e -> {
                if (!(e.getFilePj() == null && e.getPJConditionnel() && e.getCodStatut() != null && e.getCodStatut().equals(NomenclatureUtils.TYP_STATUT_PIECE_NON_CONCERNE))) {
                    listeExportPj.add(new ExportDossierPj(e.getLibPj(), e.getLibStatut(), e.getCommentaire()));
                }
            });
            // listePj.forEach(e->listeExportPj.add(new
            // ExportDossierPj(e.getLibPj(),e.getLibStatut(),e.getCommentaire())));
            motivationAvisController.getMotivationAvisEnServiceByCtrCand(commission.getCentreCandidature()).forEach(e -> listeMotivationAvis.add(new ExportDossierMotivationAvis(i18nController.getI18nTraduction(e.getI18nLibMotiv()))));
            typeDecisionController.getTypeDecisionsEnServiceByCtrCand(commission.getCentreCandidature()).forEach(e -> listeAvis.add(new ExportDossierAvis(i18nController.getI18nTraduction(e.getI18nLibTypDec()), e.getTypeAvis().getCodTypAvis())));
            listeAvis.sort((p1, p2) -> p1.getOrder().compareTo(p2.getOrder()));
        } else {
            listePj.forEach(e -> {
                final ExportDossierPj exportDossierPj = new ExportDossierPj(e.getLibPj(), e.getLibStatut(), e.getCommentaire());
                if (e.getFilePj() != null && e.getFilePj().getFileFichier() != null) {
                    exportDossierPj.setLibFichier(e.getFilePj().getNomFichier());
                }
                listeExportPj.add(exportDossierPj);
            });
        }
        final ExportDossierDate listeDates = new ExportDossierDate(MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datRetourForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datConfirmForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datJuryForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datPubliForm.getName()));
        final IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
        // 2) Create fields metadata to manage lazy loop (#foreach velocity) for table
        // row.
        /* FieldsMetadata metadata = report.createFieldsMetadata(); metadata.load(
			 * "cursusInterne", ExportDossierCursusInterne.class, true ); */
        // 3) Create context Java model
        final IContext context = report.createContext();
        // Register project
        context.put("dateheure", formatterDateTime.format(LocalDateTime.now()));
        context.put("adresseEcandidat", loadBalancingController.getApplicationPathForCandidat());
        context.put("candidature", exportCandidature);
        context.put("candidat", exportCandidat);
        context.put("bac", exportDossierBac);
        context.put("cursusInternes", listeCursusInterne);
        context.put("affichageCursusInterne", listeCursusInterne.size() > 0);
        context.put("cursusExternes", listeCursusExterne);
        context.put("affichageCursusExterne", listeCursusExterne.size() > 0);
        context.put("stages", listeStage);
        context.put("affichageStage", listeStage.size() > 0);
        context.put("cursusPros", listeCursusPro);
        context.put("affichageCursusPro", listeCursusPro.size() > 0);
        context.put("listeAvis", listeAvis);
        context.put("listeMotivationAvis", listeMotivationAvis);
        context.put("dates", listeDates);
        context.put("listePiecesJustifs", listeExportPj);
        context.put("non-dematerialisation", !isDematerialisation);
        context.put("affichagePjDemat", (listeExportPj.size() > 0 && isDematerialisation));
        // 4) Generate report by merging Java model with the Docx
        final Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF);
        report.convert(context, options, out);
        in.close();
        return out.getInputStream();
    } catch (final Exception e) {
        return null;
    } finally {
        // fermeture des fichiers
        MethodUtils.closeRessource(in);
        MethodUtils.closeRessource(out);
    }
}
Also used : Options(fr.opensagres.xdocreport.converter.Options) IContext(fr.opensagres.xdocreport.template.IContext) ExportDossierAvis(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierAvis) ExportDossierCursusPro(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusPro) Commission(fr.univlorraine.ecandidat.entities.ecandidat.Commission) SecurityCommission(fr.univlorraine.ecandidat.services.security.SecurityCommission) ArrayList(java.util.ArrayList) ExportDossierCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidat) Candidat(fr.univlorraine.ecandidat.entities.ecandidat.Candidat) ExportLettreCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportLettreCandidat) ExportDossierCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidat) ExportDossierCursusExterne(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusExterne) ExportDossierCandidature(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidature) ExportDossierBac(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierBac) ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ExportDossierCursusInterne(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusInterne) ExportDossierMotivationAvis(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierMotivationAvis) IOException(java.io.IOException) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException) CompteMinima(fr.univlorraine.ecandidat.entities.ecandidat.CompteMinima) ExportDossierDate(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierDate) ExportDossierPj(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierPj) ExportDossierStage(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierStage) Formation(fr.univlorraine.ecandidat.entities.ecandidat.Formation)

Example 5 with Options

use of fr.opensagres.xdocreport.converter.Options in project esup-ecandidat by EsupPortail.

the class CandidatureController method generateLettre.

/**
 * @param  template
 * @param  data
 * @param  fichierSignature
 * @param  locale
 * @param  sendNotification
 * @return                  l'inputstram de la lettre
 */
public InputStream generateLettre(final InputStream template, final ExportLettreCandidat data, final InputStream fichierSignature, final String locale, final Boolean sendNotification) {
    // InputStream template = MethodUtils.getXDocReportTemplate(templateLettre, locale, cacheController.getLangueDefault().getCodLangue());
    if (template == null) {
        return null;
    }
    final ByteArrayInOutStream out = new ByteArrayInOutStream();
    try {
        /* Ajout date et heure */
        data.setDateHeure(formatterDateTime.format(LocalDateTime.now()));
        data.setDate(formatterDate.format(LocalDateTime.now()));
        /* Generation du template */
        final IXDocReport report = XDocReportRegistry.getRegistry().loadReport(template, TemplateEngineKind.Velocity);
        /* Variables */
        final IContext context = report.createContext();
        context.put("data", data);
        /* Pour l'image */
        final FieldsMetadata metadata = new FieldsMetadata();
        if (fichierSignature != null) {
            metadata.addFieldAsImage("imageSignature");
            final IImageProvider originalSizeLogo = new ByteArrayImageProvider(fichierSignature, true);
            context.put("imageSignature", originalSizeLogo);
        } else {
            /* Si pas de fichier, on supprime l'image */
            metadata.addFieldAsImage("imageSignature", NullImageBehaviour.RemoveImageTemplate);
        }
        report.setFieldsMetadata(metadata);
        /* On vérifie si on affiche le tableau de signataire */
        if (data.getLibelleSignature().equals("") && fichierSignature == null) {
            context.put("showSignataire", false);
        } else {
            context.put("showSignataire", true);
        }
        /* Transformation en pdf */
        final Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF);
        report.convert(context, options, out);
        return pdfManager.cryptAndSignPdf(out, new Locale(locale != null ? locale : "fr"));
    } catch (final Exception e) {
        // probleme de taille de signature XDocConverterException + StackOverflowError
        if (e.getClass() != null && e instanceof XDocConverterException && e.getCause() != null && e.getCause() instanceof StackOverflowError) {
            if (sendNotification) {
                Notification.show(applicationContext.getMessage("candidature.lettre.download.sign.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
            }
        } else {
            if (sendNotification) {
                Notification.show(applicationContext.getMessage("candidature.lettre.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
            }
            logger.error("erreur a la création de la lettre", e);
        }
        return null;
    } finally {
        // fermeture des fichiers
        MethodUtils.closeRessource(fichierSignature);
        MethodUtils.closeRessource(template);
        MethodUtils.closeRessource(out);
    }
}
Also used : Locale(java.util.Locale) Options(fr.opensagres.xdocreport.converter.Options) ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) FieldsMetadata(fr.opensagres.xdocreport.template.formatter.FieldsMetadata) IImageProvider(fr.opensagres.xdocreport.document.images.IImageProvider) IContext(fr.opensagres.xdocreport.template.IContext) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) ByteArrayImageProvider(fr.opensagres.xdocreport.document.images.ByteArrayImageProvider) IOException(java.io.IOException) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Aggregations

Options (fr.opensagres.xdocreport.converter.Options)6 IContext (fr.opensagres.xdocreport.template.IContext)5 IXDocReport (fr.opensagres.xdocreport.document.IXDocReport)4 XDocReportException (fr.opensagres.xdocreport.core.XDocReportException)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 XDocConverterException (fr.opensagres.xdocreport.converter.XDocConverterException)2 FieldsMetadata (fr.opensagres.xdocreport.template.formatter.FieldsMetadata)2 ByteArrayInOutStream (fr.univlorraine.ecandidat.utils.ByteArrayInOutStream)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 Project (com.gpcoder.model.Project)1 IConverter (fr.opensagres.xdocreport.converter.IConverter)1 ByteArrayImageProvider (fr.opensagres.xdocreport.document.images.ByteArrayImageProvider)1 IImageProvider (fr.opensagres.xdocreport.document.images.IImageProvider)1 Candidat (fr.univlorraine.ecandidat.entities.ecandidat.Candidat)1 Commission (fr.univlorraine.ecandidat.entities.ecandidat.Commission)1 CompteMinima (fr.univlorraine.ecandidat.entities.ecandidat.CompteMinima)1 Formation (fr.univlorraine.ecandidat.entities.ecandidat.Formation)1