We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Create pdf's using multi threading

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());
}

@surya95

Please note that Aspose.PDF for Java is multi-thread safe as long as single thread works on a single document at a time. Which means access to single document by multiple threads at the same time is not supported.

Could you please share some more detail about your requirement?

If you see above code fillPdf() method we are creating new document every time so that it is not being shared among the threads as far as i understand. Please let me know whether my understanding is right?

If that is the case then i should not be getting the issue.

Requirement: We need to generate the multiple pdf documents by appending to the existing parent document and the content we are appending in each pdf is different. We are trying to use multi threading so that the documents generation can be parallel.

@surya95

Could you please share your input PDF files here for testing? We will investigate the issue and provide you more information on it.

Here is the sample input pdf filesample.pdf (11.1 KB)

@surya95

We have tested the scenario using the latest version of Aspose.PDF for Java 22.7 and have not faced any exception. So, please use Aspose.PDF for Java 22.7.