Hello all, We moved from using iText to PDFBox to stamp our PDFs before serving to our customers. We occasionally run out of our 4GB heap space on weblogic (2gb taken up by pdfs being stamped) during our busy periods. Before we consider scaling out, I'd like to know if there is any code improvements that can be done to the below stamping code to improve performance. Is stamping after loading into memory the only way to go about this?
Thanks in advance! public static void stampDocument(String pdfPath, String stampText, HttpServletResponse response) throws IOException { try (PDDocument doc = PDDocument.load(new File(pdfPath))) { if (doc.isEncrypted()) { try { doc.setAllSecurityToBeRemoved(true); } catch (Exception e) { log.error("The document is encrypted and we can't decrypt it. {}", e.getMessage()); } } PDPageTree allPages = doc.getDocumentCatalog().getPages(); float fontSize = 7; int margin = 30; for (PDPage page : allPages) { PDRectangle box = page.getCropBox(); if (box == null) { box = page.getMediaBox(); } PDFont font = PDType1Font.HELVETICA; float titleWidth = (font.getStringWidth(text) / 1000) * fontSize; float titleHeight = (font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000) * fontSize; float startX = (box.getWidth() - titleWidth) / 2; float startY = page.getMediaBox().getLowerLeftY() + margin - titleHeight; try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true)) { contentStream.beginText(); contentStream.setFont(font, fontSize); contentStream.setStrokingColor(Color.BLACK); contentStream.setLeading(10); contentStream.newLineAtOffset(startX, startY); contentStream.showText(text); contentStream.endText(); contentStream.closeAndStroke(); } } doc.save(new BufferedOutputStream(response.getOutputStream())); } }