-
Notifications
You must be signed in to change notification settings - Fork 3
/
PrintBacking.java
88 lines (73 loc) · 2.78 KB
/
PrintBacking.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package org.softuni.exam.web.beans.document;
import org.omnifaces.util.Faces;
import org.softuni.exam.domain.models.view.document.DocumentDetailsViewModel;
import org.softuni.exam.services.DocumentService;
import org.softuni.exam.util.PdfMaker;
import org.softuni.exam.web.beans.BaseBackingBean;
import javax.annotation.PostConstruct;
import javax.faces.annotation.RequestParameterMap;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.logging.Level;
@Named
@ViewScoped
public class PrintBacking extends BaseBackingBean implements Serializable {
private static final long serialVersionUID = 1L;
private DocumentDetailsViewModel model = new DocumentDetailsViewModel();
@Inject
private transient DocumentService service;
@Inject
private PdfMaker pdfMaker;
@Inject
@RequestParameterMap
private Map<String, String> requestMap;
@PostConstruct
public void init() {
String id = requestMap.get("id");
model = service
.findById(id, DocumentDetailsViewModel.class)
.orElseThrow(() -> new NoResultException("Document not found"));
}
public DocumentDetailsViewModel getModel() {
return model;
}
public void print() {
String id = requestMap.get("id");
if (service.print(id)) {
redirect("/home");
} else {
addMessage("Printing failed. Please retry or contact support.");
}
}
public void downloadAsPdf() {
pdfMaker
.markdownToPdf(model.getTitle(), model.getContent())
.ifPresentOrElse(
this::sendPdf,
addMessageRunnable("Converting to PDF failed. Please retry or contact support.")
);
}
private void sendPdf(byte[] asPdf) {
String filename = requestMap.get("id") + ".pdf";
HttpServletResponse response = Faces.getResponse();
// Details: https://stackoverflow.com/a/9394237/7598851
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setContentLength(asPdf.length);
response.setCharacterEncoding("UTF-8");
try (OutputStream output = response.getOutputStream()) {
output.write(asPdf);
} catch (IOException e) {
logger.log(Level.SEVERE, "Write to response output stream failed", e);
addMessage("Sending PDF file failed. Please retry or contact support.");
}
}
}