Getting the concurrent exceptions while generating multiple pdf’s using java multi threading. can you please provide us solution to get rid of this issue.
The following is the sample code for reference.
private static void genPdfConcurrent() {
String path = “sample_pdf_path”;
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<?>> list = new ArrayList<>();
for (int i=0; i<5; i++) {
list.add(executorService.submit(() -> {
try {
fillPdf(path);
} catch (IOException e) {
e.printStackTrace();
}
}));
}
for (Future<?> future : list) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
private static void fillPdf(String filePath) throws IOException {
com.aspose.pdf.Document document = new com.aspose.pdf.Document(filePath);
document.getPages().add();
int lastPage = document.getPages().size();
Page pdfPage = document.getPages().get_Item(lastPage);
String content = "<p><strong>Default</strong>sample html content</p>";
for (int i=0; i<10; i++) {
try {
String originalContent = new String(content.getBytes(), StandardCharsets.UTF_8);
HtmlFragment htmlFragment = new HtmlFragment(originalContent);
MarginInfo marginInfo = new MarginInfo();
marginInfo.setLeft(50);
marginInfo.setBottom(30);
htmlFragment.setMargin(marginInfo);
pdfPage.getParagraphs().add(htmlFragment);
} catch (Exception e) {
e.printStackTrace();
}
}
File txtFragmentsPdfFile = File.createTempFile("~sample~", ".pdf");
document.save(txtFragmentsPdfFile.getPath());
}