I have a Java method that generates PDFs from HTML templates using the iText 7 library. The method works fine for generating a small number of PDFs, but when I try to run this code with 10 threads and generating a large number (e.g., 1000), I encounter an out-of-memory error.Heap size increasing upto 1GB.
And also i am using a base64 String of Signature and Letterhead images.
Java
public byte[] startPdfCreation(String template, PdfConfiguration configuration, Map<String, String> notice) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(outputStream);
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.setDefaultPageSize(PageSize.A4);
Document document = new Document(pdfDocument);
document.setLeftMargin(26);
document.setRightMargin(26);
String letterhead = getLetterheadImage(configuration);
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new BackgroundImageHandler(letterhead));
String signature = getSignatureImage(configuration);
ConverterProperties properties = getConverterProperties();
String substitutedTemplate = substituteValues(template, notice);
List<IElement> elements = HtmlConverter.convertToElements(substitutedTemplate, properties);
for (IElement element : elements) {
document.add((BlockElement) element);
}
document.close();
pdfDocument.close();
return outputStream.toByteArray();
} catch (Exception e) {
log.error("error while creating a pdf", e);
}
return new byte[0];
}
Here i am using executor service to run in 10 threads
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
CompletableFuture<Void> allTasks = CompletableFuture.allOf(
noticeDataList.stream()
.map(notice -> CompletableFuture.runAsync(() -> {
PdfConfiguration pdfConfiguration = createPdfConfiguration(notice);
byte[] fileContent = startPdfCreation(template, pdfConfiguration, notice);
Map<String, String> uploadResponse = uploadPdf(fileContent, notice);
if (uploadResponse != null) {
successFiles.add(notice);
} else {
failedFiles.add(notice);
}
}, executor))
.toArray(CompletableFuture[]::new)
);
return allTasks.thenApply(result -> {
executor.shutdown();
return new PdfGenerateResponse(successFiles, failedFiles);
}).join();
Is there is something i am missing or what please help me out
Thanks.
How i can create upto 1000 pdf using Threads in minimum heap memory usage.
Tausif Presolv 360 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.