Commit 80f5d592 authored by Viraj Shah's avatar Viraj Shah

Add new PDF result type

parent 208a9b77
Pipeline #113356 passed with stages
in 41 seconds
......@@ -3,6 +3,8 @@ package ic.doc;
import ic.doc.web.HTMLResultPage;
import ic.doc.web.IndexPage;
import ic.doc.web.MarkdownResultPage;
import ic.doc.web.PDFResultPage;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
......@@ -38,7 +40,7 @@ public class WebServer {
} else if (resultFormat.toLowerCase().equals("markdown")) {
new MarkdownResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
} else if (resultFormat.toLowerCase().equals("pdf")) {
// new PDFResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
new PDFResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
} else {
//Intentionally redirect to HTML on error to avoid cluttering with files
new HTMLResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
......
package ic.doc.web;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;
public class PDFResultPage extends MarkdownResultPage {
private static final String TEMP_MD_PATH = "/tmp/result.md";
private static final String TEMP_PDF_PATH = "/tmp/result.pdf";
public PDFResultPage(String query, String answer) {
super(query, answer);
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=result.pdf");
File md = new File(TEMP_MD_PATH);
FileWriter fileWriter = new FileWriter(md);
fileWriter.write(createMarkdownText());
fileWriter.close();
File pdf = convertToPDF(md);
Files.copy(pdf.toPath(), resp.getOutputStream());
deleteFile(pdf);
deleteFile(md);
}
private File convertToPDF(File markdown) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("pandoc", TEMP_MD_PATH, "-s",
"-o", TEMP_PDF_PATH);
Process process = processBuilder.start();
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return new File(TEMP_PDF_PATH);
}
private void deleteFile(File file) throws IOException{
if (!file.delete()) {
throw new IOException("Cannot Delete File "+ file.getAbsolutePath());
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment