Untitled
user_7668146059
java
4 years ago
2.5 kB
15
Indexable
private ModelAndView createContract(Map<String, Object> contractor, ModelAndView mv) {
try {
// Initial setup, create credentials instance.
Credentials credentials = Credentials.serviceAccountCredentialsBuilder()
.fromFile("pdfservices-api-credentials.json")
.build();
//Create an ExecutionContext using credentials and create a new operation instance.
ExecutionContext executionContext = ExecutionContext.create(credentials);
CreatePDFOperation htmlToPDFOperation = CreatePDFOperation.createNew();
// Set operation input from a source file.
FileRef source = FileRef.createFromLocalFile("src/main/webapp/WEB-INF/jsp/st/contractors/index.zip");
htmlToPDFOperation.setInput(source);
// Provide any custom configuration options for the operation
// We pass person data here to dynamically fill out the HTML
setCustomOptionsAndPersonData(htmlToPDFOperation, contractor.get("workers["+1+"][full_name]"));
// Execute the operation.
FileRef result = htmlToPDFOperation.execute(executionContext);
// Save the result to the specified location. Delete previous file if exists
File file = new File(contractFilePath);
Files.deleteIfExists(file.toPath());
result.saveAs(file.getPath());
} catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) {
LOG.error("Exception encountered while executing operation", ex);
}
mv.setViewName("jsonView");
return mv;
}
private static void setCustomOptionsAndPersonData(CreatePDFOperation htmlToPDFOperation, Object str) {
//Set the dataToMerge field that needs to be populated in the HTML before its conversion
JSONObject dataToMerge = new JSONObject();
dataToMerge.put("contractorWorker", str);
// Set the desired HTML-to-PDF conversion options.
CreatePDFOptions htmlToPdfOptions = CreatePDFOptions.htmlOptionsBuilder()
.includeHeaderFooter(false)
.withDataToMerge(dataToMerge)
.build();
htmlToPDFOperation.setOptions(htmlToPdfOptions);
}
@RequestMapping(value="/st/contractors/pdf.do")
public void downloadContract(HttpServletResponse response) {
Path file = Paths.get(contractFilePath);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=econtract.pdf");
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}Editor is loading...