use of fr.opensagres.xdocreport.core.XDocReportException in project esup-ecandidat by EsupPortail.
the class CandidatureController method downloadDossier.
/**
* telecharge le dossier
* @param candidature
* @param listePresentation
* @param listeDatePresentation
* @param listePj
* @param listeForm
* @param addPj
* @return l'InputStream du dossier
*/
public OnDemandFile downloadDossier(final Candidature candidature, final List<SimpleTablePresentation> listePresentation, final List<SimpleTablePresentation> listeDatePresentation, final List<PjPresentation> listePj, final List<FormulairePresentation> listeForm, final Boolean addPj) {
/* Variables utiles */
final String numDossier = candidature.getCandidat().getCompteMinima().getNumDossierOpiCptMin();
final String nom = candidature.getCandidat().getNomPatCandidat();
final String prenom = candidature.getCandidat().getPrenomCandidat();
final String codForm = candidature.getFormation().getCodForm();
final String libForm = candidature.getFormation().getLibForm();
/* Nom du fichier */
final String fileName = applicationContext.getMessage("candidature.download.file", new Object[] { numDossier, nom, prenom, codForm }, UI.getCurrent().getLocale());
// Les parametres des PJ
final Boolean enableAddApogeePJDossier = parametreController.getIsAddApogeePJDossier();
// Font
final PDFont font = PDType1Font.HELVETICA_BOLD;
// le dossier outStream
ByteArrayInputStream bisDossier = null;
// liste des InputStream à fermer
final List<InputStream> listeInputStreamToClose = new ArrayList<>();
/* Génération du dossier principal */
try {
bisDossier = generateDossier(candidature, listePresentation, listeDatePresentation, listePj, listeForm);
if (bisDossier == null) {
Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
return null;
}
} catch (IOException | XDocReportException e2) {
Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
logger.error("erreur a la génération du dossier", e2);
return null;
}
ByteArrayInOutStream out = new ByteArrayInOutStream();
InputStream is = null;
try {
/* Merger */
final PDFMergerUtility ut = new PDFMergerUtility();
/* Propriétés du document */
final PDDocumentInformation info = new PDDocumentInformation();
info.setTitle(numDossier + "_" + nom + "_" + prenom + "_" + codForm);
info.setAuthor(ConstanteUtils.APP_NAME);
info.setSubject(nom + " " + prenom + " (" + numDossier + ") / " + libForm + " (" + codForm + ")");
final Calendar calendar = Calendar.getInstance(UI.getCurrent().getLocale());
info.setCreationDate(calendar);
info.setModificationDate(calendar);
ut.setDestinationDocumentInformation(info);
/* Ajout du dossier */
ut.addSource(bisDossier);
/* Gestion des erreurs de pj */
Boolean errorAddPj = false;
final List<String> fileNameError = new ArrayList<>();
/* Calcul si besoin d'ajouter les pj */
Integer nbFilePJ = 0;
for (final PjPresentation pj : listePj) {
if (pj.getFilePj() != null) {
nbFilePJ++;
}
}
if (addPj && nbFilePJ > 0 && !fileController.isFileServiceMaintenance(applicationContext.getMessage("file.service.maintenance.dossier", null, UI.getCurrent().getLocale()))) {
for (final PjPresentation e : listePj) {
// listePj.forEach(e->{
try {
// titre header
final String textHeader = e.getLibPj();
// PJ doit etre à true
if (e.getFilePj() != null && (e.getPjCandidatFromApogee() == null || (e.getPjCandidatFromApogee() != null && enableAddApogeePJDossier))) {
final Fichier file = e.getFilePj();
final String nameFile = file.getNomFichier();
final InputStream inputStreamFile = fileController.getInputStreamFromPjPresentation(e);
// on doit fermer l'inputStream apres le merge donc je stock le stream et le ferme apres
listeInputStreamToClose.add(inputStreamFile);
// cas du PDF
if (inputStreamFile != null && MethodUtils.isPdfFileName(nameFile)) {
// chargement du pdf avant de l'ajouter -> evite de compiler avec des fichiers corrompus
final BufferedInputStream bufferedInputStreamFile = new BufferedInputStream(inputStreamFile);
// on doit fermer l'inputStream apres le merge donc je stock le stream et le ferme apres
listeInputStreamToClose.add(bufferedInputStreamFile);
try {
// on place un marker au max du buffer du stream (mark = nb byte qu'il peut lire avant d'etre invalide.. mais comme on lit tout le fichier..)
bufferedInputStreamFile.mark(ConstanteUtils.MAX_BUFFER_SIZE);
// lecture du fichier pour vérifier s'il n'est pas corrompue
final PDDocument doc = PDDocument.load(bufferedInputStreamFile);
// cloture immédiate du fichier pour libérer la mémoire
MethodUtils.closeRessource(doc);
// on replace le bufferedInputStreamFile au début
bufferedInputStreamFile.reset();
// on ajoute l'inputStream
ut.addSource(bufferedInputStreamFile);
} catch (final Exception ex1) {
logger.warn("fichier pdf '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", ex1);
errorAddPj = true;
fileNameError.add(nameFile);
}
} else if (inputStreamFile != null && MethodUtils.isImgFileName(nameFile)) {
// creation document
final PDDocument document = new PDDocument();
final ByteArrayInOutStream baosImg = new ByteArrayInOutStream();
ByteArrayInputStream bis = null;
try {
// chargement page A4
final PDRectangle PAGE_SIZE_A4 = PDRectangle.A4;
// creation page
final PDPage page = new PDPage(PAGE_SIZE_A4);
// ajout de la page
document.addPage(page);
// Stream du document
final PDPageContentStream contentStream = new PDPageContentStream(document, page);
// margin top est calculée si un text de titre a été ajouté
Float marginTop = addHeaderPJ(textHeader, font, PAGE_SIZE_A4, contentStream);
// on ajoute la marge sous le text (ou la marge depuis le haut du doc si pas de
// text)
marginTop = marginTop + ConstanteUtils.DOSSIER_MARGIN;
// creation de l'image
PDImageXObject img = null;
// JPG
if (MethodUtils.isJpgFileName(nameFile)) {
img = JPEGFactory.createFromStream(document, inputStreamFile);
} else // PNG
if (MethodUtils.isPngFileName(nameFile)) {
img = LosslessFactory.createFromImage(document, ImageIO.read(inputStreamFile));
}
// calcul de la largeur et hauteur de l'image
Float imgWidth = (float) img.getWidth();
Float imgHeight = (float) img.getHeight();
// calcul de la largeur et hauteur de la page moins les deux marges
final Float a4Width = PAGE_SIZE_A4.getWidth() - 2 * ConstanteUtils.DOSSIER_MARGIN;
final Float a4Height = PAGE_SIZE_A4.getHeight() - ConstanteUtils.DOSSIER_MARGIN - marginTop;
// calcul du coef à appliquer si l'image est trop grande
Float coef = 1.0f;
if (imgWidth > a4Width) {
coef = a4Width / imgWidth;
imgWidth = imgWidth * coef;
imgHeight = imgHeight * coef;
}
// le nouveau coef
if (imgHeight > a4Height) {
coef = a4Height / imgHeight;
imgWidth = imgWidth * coef;
imgHeight = imgHeight * coef;
}
// ecriture de l'image
contentStream.drawImage(img, ConstanteUtils.DOSSIER_MARGIN, PAGE_SIZE_A4.getHeight() - imgHeight - marginTop, imgWidth, imgHeight);
// il faut d'abord fermer le flux
MethodUtils.closeRessource(contentStream);
document.save(baosImg);
/* Creation du flux */
bis = baosImg.getInputStream();
/* Ajout de la page au document */
ut.addSource(bis);
} catch (final Exception e1) {
errorAddPj = true;
fileNameError.add(nameFile);
logger.warn("fichier image '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", e1);
} finally {
/* Nettoyage des ressources */
MethodUtils.closeRessource(document);
MethodUtils.closeRessource(bis);
MethodUtils.closeRessource(baosImg);
}
}
}
} catch (final Exception e1) {
errorAddPj = true;
final String nameFile = e.getFilePj() != null ? e.getFilePj().getNomFichier() : "-";
if (e.getFilePj() != null) {
fileNameError.add(e.getFilePj().getNomFichier());
}
logger.warn("fichier '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", e1);
}
}
}
if (errorAddPj) {
String fileNamesError = "";
if (fileNameError.size() > 0) {
fileNamesError = " : " + fileNameError.stream().collect(Collectors.joining(", "));
}
Notification.show(applicationContext.getMessage("candidature.download.encoding.pj", null, UI.getCurrent().getLocale()) + fileNamesError, Type.WARNING_MESSAGE);
}
ut.setDestinationFileName(fileName);
ut.setDestinationStream(out);
ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
is = pdfManager.cryptAndSignPdf(out, UI.getCurrent().getLocale());
return new OnDemandFile(fileName, is);
} catch (final Exception e) {
logger.warn("erreur a la génération du dossier '" + fileName + "'", e);
try {
out = new ByteArrayInOutStream();
final PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(generateDossier(candidature, listePresentation, listeDatePresentation, listePj, listeForm));
ut.setDestinationFileName(fileName);
ut.setDestinationStream(out);
ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
is = pdfManager.cryptAndSignPdf(out, UI.getCurrent().getLocale());
Notification.show(applicationContext.getMessage("candidature.download.error.pj", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
return new OnDemandFile(fileName, is);
} catch (final Exception e2) {
Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
logger.error("erreur a la génération du dossier", e2);
return null;
}
} finally {
// fermeture des fichiers
MethodUtils.closeRessource(is);
MethodUtils.closeRessource(out);
MethodUtils.closeRessource(bisDossier);
/* besoin de fermer les pdf apres coup */
listeInputStreamToClose.forEach(inputStreamFile -> {
MethodUtils.closeRessource(inputStreamFile);
});
listeInputStreamToClose.clear();
}
}
use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.
the class TemplateEngine method generateDocumentDocx.
public byte[] generateDocumentDocx(Properties properties, File templateFile) throws DocumentTemplateException {
try {
FileInputStream templateInputStream = new FileInputStream(templateFile);
IXDocReport report = readXDocReport(templateInputStream);
IContext context = report.createContext();
for (Object key : properties.keySet()) {
if (key instanceof String) {
Object property = properties.get(key);
// Sanitize property to avoid XML parsing errors
if (property instanceof Enum<?> && property.toString() != null) {
property = returnSanitizedString(property.toString());
} else if (property instanceof String) {
property = returnSanitizedString((String) property);
}
if (property != null && !(property instanceof String && ((String) property).isEmpty())) {
context.put((String) key, property);
}
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
report.process(context, outputStream);
return outputStream.toByteArray();
} catch (IOException | XDocReportException | VelocityException e) {
throw new DocumentTemplateException(String.format(I18nProperties.getString(Strings.errorDocumentGeneration), templateFile.getName()));
}
}
use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.
the class TemplateEngine method extractTemplateVariablesDocx.
public DocumentVariables extractTemplateVariablesDocx(File templateFile) throws DocumentTemplateException {
try {
FileInputStream templateInputStream = new FileInputStream(templateFile);
IXDocReport report = readXDocReport(templateInputStream);
FieldsExtractor<FieldExtractor> extractor = FieldsExtractor.create();
report.extractFields(extractor);
return filterExtractedVariables(extractor);
} catch (XDocReportException | IOException e) {
throw new DocumentTemplateException(String.format(I18nProperties.getString(Strings.errorReadingTemplate), templateFile.getName()));
}
}
use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.
the class TemplateEngine method readXDocReport.
protected IXDocReport readXDocReport(InputStream templateInputStream) throws DocumentTemplateException {
ByteArrayOutputStream outStream;
try {
// Sanitize docx template for XXEs
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
wordMLPackage.getDocumentModel();
outStream = new ByteArrayOutputStream();
wordMLPackage.save(outStream);
} catch (Docx4JException | NullPointerException e) {
throw new DocumentTemplateException(I18nProperties.getString(Strings.errorTemplateFileCorrupt));
}
try {
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
ITemplateEngine templateEngine = new XDocTemplateEngine(xdocVelocityProperties);
return XDocReportRegistry.getRegistry().loadReport(inStream, templateEngine);
} catch (IOException | XDocReportException | NullPointerException e) {
throw new DocumentTemplateException(I18nProperties.getString(Strings.errorProcessingTemplate));
}
}
use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.
the class TemplateEngine method validateTemplateDocx.
public void validateTemplateDocx(InputStream templateInputStream) throws DocumentTemplateException {
try {
IXDocReport report = readXDocReport(templateInputStream);
FieldsExtractor<FieldExtractor> extractor = FieldsExtractor.create();
report.extractFields(extractor);
} catch (XDocReportException | IOException e) {
throw new DocumentTemplateException(I18nProperties.getString(Strings.errorProcessingTemplate));
}
}
Aggregations