The issue is that in PDFBox 3.x, the font constants have been moved to a different class. You need to use Standard14Fonts instead. Here's the corrected code:
@SuppressWarnings("null")
public boolean generateChallanPDF(GeMChallanDataBean challanBean, HttpServletResponse response, HttpServletRequest request, int isEmail, String challanTokenID) throws WSApplicationServiceException {
try {
SimpleDateFormat month = new SimpleDateFormat("MM");
SimpleDateFormat date = new SimpleDateFormat("dd");
SimpleDateFormat year = new SimpleDateFormat("YYYY");
Date currDate = new Date();
Long challanTxnID = Long.parseLong(challanBean.getChallanDetailID());
Map<String, Object> stateDetail = null;
if (!ObjectUtils.isEmpty(commonService.getModifiedOrgDetail(challanTxnID))) {
stateDetail= commonService.getModifiedOrgDetail(challanTxnID).get(0);
}else {
stateDetail= commonService.getOrgDetail(challanBean.getOrgCode()).get(0);
}
String treasuryInputMode = String.valueOf(stateDetail.get("TREASURYCODEINPUTMODE"));
int isTreasuryRequired = Integer.parseInt(stateDetail.get("ISTREASURYCODEREQUIRED").toString());
List<Map<String, Object>> challanDetail = getChallanData(challanTxnID);
List<Map<String, Object>> refundDetail = getRefundData(challanBean.getGemUniqueBidID());
String blockRequestID= !ObjectUtils.isEmpty(challanDetail.get(0).get("blockRequestID")) ? challanDetail.get(0).get("blockRequestID").toString() : "-";
String path = basePath+challanSavePath+"/"+stateDetail.get("ORGCODE").toString()+"/"+year.format(currDate)+"/"+month.format(currDate)+"/"+date.format(currDate);
String challanFileName = "Challan"+challanBean.getChallanDetailID()+"-"+stateDetail.get("ORGCODE").toString()+"-GeM-"+date.format(currDate)+"-"+month.format(currDate)+"-"+year.format(currDate)+".pdf";
String logo = null;
if(!ObjectUtils.isEmpty(stateDetail.get("ORGLOGO"))) {
logo = "data:image/png;base64,"+commonService.bytesToBase64Binary((byte[])stateDetail.get("ORGLOGO"));
}
if(!new File(path+"/"+challanFileName).exists()) {
PDDocument document = null;
File dir = new File(path);
if (!dir.exists()) dir.mkdirs();
try {
document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
logger.info("generateChallanPDF method:inside document:");
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// Set up fonts - CORRECTED for PDFBox 3.x
PDFont fontBold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);
PDFont fontNormal = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
float fontSize = 9;
float titleFontSize = 15;
float bodyFontSize = 11;
float margin = 50;
float yStart = page.getMediaBox().getHeight() - margin;
float yPosition = yStart;
float tableWidth = page.getMediaBox().getWidth() - 2 * margin;
// Header with logos
float currentY = yPosition;
// Draw organization logo if available
if (stateDetail.get("ORGLOGO") != null) {
try {
byte[] orgLogoBytes = (byte[]) stateDetail.get("ORGLOGO");
PDImageXObject orgLogoImage = PDImageXObject.createFromByteArray(document, orgLogoBytes, "org_logo");
float orgLogoWidth = 100;
float orgLogoHeight = 35;
contentStream.drawImage(orgLogoImage, margin, currentY - orgLogoHeight, orgLogoWidth, orgLogoHeight);
} catch (Exception e) {
logger.error("Error drawing organization logo", e);
}
}
// Draw GeM logo
try {
InputStream logoStream = null;
PDImageXObject gemLogoImage = null;
logoStream = getClass().getClassLoader().getResourceAsStream("static-images/gem-logo.png");
if (logoStream != null) {
gemLogoImage = PDImageXObject.createFromByteArray(document,
IOUtils.toByteArray(logoStream), "gem_logo");
}
if (gemLogoImage == null) {
logoStream = request.getServletContext().getResourceAsStream("/resources/static-images/gem-logo.png");
if (logoStream != null) {
gemLogoImage = PDImageXObject.createFromByteArray(document,
IOUtils.toByteArray(logoStream), "gem_logo");
}
}
if (gemLogoImage == null) {
String logoPath = request.getServletContext().getRealPath("/resources/static-images/gem-logo.png");
if (logoPath != null && new File(logoPath).exists()) {
gemLogoImage = PDImageXObject.createFromFile(logoPath, document);
}
}
if (gemLogoImage != null) {
float gemLogoWidth = 100;
float gemLogoHeight = 35;
float gemLogoX = page.getMediaBox().getWidth() - margin - gemLogoWidth;
contentStream.drawImage(gemLogoImage, gemLogoX, currentY - gemLogoHeight, gemLogoWidth, gemLogoHeight);
}
} catch (Exception e) {
logger.error("Error loading GeM logo", commonService.getStackTraceToString(e));
}
currentY -= 50; // Space after logos
// Title
contentStream.setFont(fontBold, bodyFontSize);
contentStream.beginText();
contentStream.newLineAtOffset(margin, currentY);
contentStream.showText(messageSource.getMessage("lbl.challan.title", null, Locale.getDefault()));
contentStream.endText();
currentY -= 20;
// Main table data
float rowHeight = 15;
float cellPadding = 5;
float col1 = margin;
float col2 = margin + tableWidth * 0.25f;
float col3 = margin + tableWidth * 0.5f;
float col4 = margin + tableWidth * 0.75f;
// Draw table rows
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.beneficiery.ac.no", null, Locale.getDefault()),
challanDetail.get(0).get("BIDVAN").toString(),
messageSource.getMessage("lbl.beneficiery.name", null, Locale.getDefault()),
challanDetail.get(0).get("BUYERPOOLACHOLDERNAME").toString(),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.beneficiery.bank.name", null, Locale.getDefault()),
challanDetail.get(0).get("BUYERPOOLBANKNAME").toString(),
messageSource.getMessage("lbl.beneficiery.bank.branch", null, Locale.getDefault()),
commonService.encodeCharacter(challanDetail.get(0).get("BUYERPOOLBRANCHNAME") == null ? "" : challanDetail.get(0).get("BUYERPOOLBRANCHNAME").toString()),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.beneficiery.ifsc.code", null, Locale.getDefault()),
challanDetail.get(0).get("BUYERPOOLACIFSC").toString(),
messageSource.getMessage("lbl.uniquebidid", null, Locale.getDefault()),
challanBean.getGemUniqueBidID(),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.amount", null, Locale.getDefault()),
challanBean.getAmtToDisp() + "\n" + "("+challanBean.getAmtInStr().replaceAll("[ ,]"," ").trim()+")",
messageSource.getMessage("lbl.ddo.code", null, Locale.getDefault()),
challanBean.getDdoCode(),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.ddo.name", null, Locale.getDefault()),
challanDetail.get(0).get("DDONAME").toString(),
messageSource.getMessage("lbl.state", null, Locale.getDefault()),
stateDetail.get("STATENAME").toString(),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.date.time", null, Locale.getDefault()),
challanBean.getChallanReqDate(),
messageSource.getMessage("lbl.organization.code", null, Locale.getDefault()),
challanBean.getOrgCode(),
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
// Block Request ID (single column)
contentStream.setFont(fontBold, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col1, currentY);
contentStream.showText(messageSource.getMessage("lbl.block.request.id", null, Locale.getDefault()));
contentStream.endText();
contentStream.setFont(fontNormal, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col2, currentY);
contentStream.showText(blockRequestID);
contentStream.endText();
currentY -= (rowHeight * 2); // Extra space
// Treasury Details
if(isTreasuryRequired==1 && treasuryInputMode.equals("1")) {
currentY = drawTreasuryDetails(contentStream, fontBold, fontNormal, bodyFontSize, fontSize,
challanDetail, messageSource, currentY, margin, tableWidth);
} else if (isTreasuryRequired==1 && treasuryInputMode.equals("2")) {
contentStream.setFont(fontBold, bodyFontSize);
contentStream.beginText();
contentStream.newLineAtOffset(margin, currentY);
contentStream.showText(messageSource.getMessage("lbl.treasury.and.other.detail", null, Locale.getDefault()));
contentStream.endText();
currentY -= rowHeight;
String treasuryDetail = commonService.removehtmltag(challanDetail.get(0).get("TREASURYDETAIL").toString());
currentY = drawWrappedText(contentStream, fontNormal, fontSize, treasuryDetail, margin, currentY, tableWidth);
currentY -= rowHeight;
}
// Refund Details
if(isTreasuryRequired==1 && treasuryInputMode.equals("1")) {
currentY -= rowHeight;
currentY = drawRefundDetails(contentStream, fontBold, fontNormal, bodyFontSize, fontSize,
refundDetail, messageSource, currentY, margin, tableWidth);
}
// Disclaimer
currentY -= rowHeight;
String disclaimerText = "Disclaimer: \n\n" +
messageSource.getMessage("lbl.challan.disclaimer", null, Locale.getDefault());
currentY = drawWrappedText(contentStream, fontNormal, fontSize, disclaimerText, margin, currentY, tableWidth);
logger.info("generateChallanPDF method::PDF created Successfully with PDFBox");
}
// Save the document
document.save(new File(path + File.separator + challanFileName));
} catch(Exception ex){
logger.error("Error generating PDF with PDFBox: " + commonService.getStackTraceToString(ex));
throw ex;
} finally{
if(document != null) {
document.close();
}
}
manageGeMChallanDAO.updateChallanFileName(challanTxnID, challanFileName);
}
// Email Challan File as Attachment
if(isEmail==1 && !ObjectUtils.isEmpty(challanBean.getEmailID())) {
EmailDataBean emailBean = new EmailDataBean();
emailBean.setEmailTemplateID(challanAttachTemplateID);
emailBean.setEmailTo(Arrays.asList(StringUtils.commaDelimitedListToStringArray(challanBean.getEmailID())).stream().distinct().toArray(String[]::new));
emailBean.setFilePath(path+"/"+challanFileName);
emailBean.setSubjectParams(new Object[] {stateDetail.get("ORGNAME").toString()});
emailBean.setBodyParams(new Object[] {stateDetail.get("ORGNAME").toString(), challanBean.getGemUniqueBidID(), challanBean.getAmtToDisp()});
if(messageService.sendEmail(emailBean)) {
return true;
} else {
return false;
}
} else if(isEmail==0) {
// Download challan pdf file
commonService.downloadFile(challanFileName, path, response);
return true;
} else {
return false;
}
} catch (Exception e) {
logger.error("In Generate Challan PDF" + commonService.getStackTraceToString(e));
throw new WSApplicationServiceException("lbl.invalid.request",commonService.generateErrorMap("Error While Generating PDF Error :- " + e.getMessage()));
}
}
// Helper method to draw table rows
private void drawTableRow(PDPageContentStream contentStream, PDFont fontBold, PDFont fontNormal,
float fontSize, String label1, String value1, String label2, String value2,
float col1, float col2, float col3, float col4, float y, float rowHeight) throws IOException {
// First label
contentStream.setFont(fontBold, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col1, y);
contentStream.showText(label1);
contentStream.endText();
// First value
contentStream.setFont(fontNormal, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col2, y);
contentStream.showText(value1);
contentStream.endText();
// Second label
contentStream.setFont(fontBold, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col3, y);
contentStream.showText(label2);
contentStream.endText();
// Second value
contentStream.setFont(fontNormal, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col4, y);
contentStream.showText(value2);
contentStream.endText();
}
// Helper method to draw treasury details
private float drawTreasuryDetails(PDPageContentStream contentStream, PDFont fontBold, PDFont fontNormal,
float bodyFontSize, float fontSize, List<Map<String, Object>> challanDetail,
MessageSource messageSource, float currentY, float margin, float tableWidth) throws IOException {
contentStream.setFont(fontBold, bodyFontSize);
contentStream.beginText();
contentStream.newLineAtOffset(margin, currentY);
contentStream.showText(messageSource.getMessage("lbl.treasury.detail.for.withdrawal", null, Locale.getDefault()));
contentStream.endText();
currentY -= 15;
float col1 = margin;
float col2 = margin + tableWidth * 0.25f;
float col3 = margin + tableWidth * 0.5f;
float col4 = margin + tableWidth * 0.75f;
float rowHeight = 12;
for(int i=0; i<challanDetail.size(); i++) {
String codeTypeName = challanDetail.get(i).get("CODETYPENAME").toString();
String val = challanDetail.get(i).get("CODE").toString();
if(!ObjectUtils.isEmpty(challanDetail.get(i).get("DESCR"))) {
val = val + (" # "+challanDetail.get(i).get("DESCR").toString());
}
if(i % 2 == 0) {
// First column pair
drawTableRow(contentStream, fontBold, fontNormal, fontSize, codeTypeName, val, "", "",
col1, col2, col3, col4, currentY, rowHeight);
} else {
// Second column pair - update the second pair
contentStream.setFont(fontBold, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col3, currentY);
contentStream.showText(codeTypeName);
contentStream.endText();
contentStream.setFont(fontNormal, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col4, currentY);
contentStream.showText(val);
contentStream.endText();
currentY -= rowHeight;
}
}
// Handle bill code and object code
if(!ObjectUtils.isEmpty(challanDetail.get(0).get("BILLCODE"))) {
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.bill.code", null, Locale.getDefault()),
challanDetail.get(0).get("BILLCODE").toString(), "", "",
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
}
if(!ObjectUtils.isEmpty(challanDetail.get(0).get("OBJECTCODE"))) {
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.object.code", null, Locale.getDefault()),
challanDetail.get(0).get("OBJECTCODE").toString(), "", "",
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
}
return currentY;
}
// Helper method to draw refund details
private float drawRefundDetails(PDPageContentStream contentStream, PDFont fontBold, PDFont fontNormal,
float bodyFontSize, float fontSize, List<Map<String, Object>> refundDetail,
MessageSource messageSource, float currentY, float margin, float tableWidth) throws IOException {
contentStream.setFont(fontBold, bodyFontSize);
contentStream.beginText();
contentStream.newLineAtOffset(margin, currentY);
contentStream.showText(messageSource.getMessage("lbl.treasury.detail.for.refund", null, Locale.getDefault()));
contentStream.endText();
currentY -= 15;
float col1 = margin;
float col2 = margin + tableWidth * 0.25f;
float col3 = margin + tableWidth * 0.5f;
float col4 = margin + tableWidth * 0.75f;
float rowHeight = 12;
for(int i=0; i<refundDetail.size(); i++) {
String codeTypeName = refundDetail.get(i).get("CODETYPENAME").toString();
String val = refundDetail.get(i).get("CODE").toString();
if(!ObjectUtils.isEmpty(refundDetail.get(i).get("DESCR"))) {
val = val + (" # "+refundDetail.get(i).get("DESCR").toString());
}
if(i % 2 == 0) {
drawTableRow(contentStream, fontBold, fontNormal, fontSize, codeTypeName, val, "", "",
col1, col2, col3, col4, currentY, rowHeight);
} else {
contentStream.setFont(fontBold, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col3, currentY);
contentStream.showText(codeTypeName);
contentStream.endText();
contentStream.setFont(fontNormal, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(col4, currentY);
contentStream.showText(val);
contentStream.endText();
currentY -= rowHeight;
}
}
if(!ObjectUtils.isEmpty(refundDetail.get(0).get("REFUNDBILLCODE"))) {
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.bill.code", null, Locale.getDefault()),
refundDetail.get(0).get("REFUNDBILLCODE").toString(), "", "",
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
}
if(!ObjectUtils.isEmpty(refundDetail.get(0).get("REFUNDOBJECTCODE"))) {
drawTableRow(contentStream, fontBold, fontNormal, fontSize,
messageSource.getMessage("lbl.object.code", null, Locale.getDefault()),
refundDetail.get(0).get("REFUNDOBJECTCODE").toString(), "", "",
col1, col2, col3, col4, currentY, rowHeight);
currentY -= rowHeight;
}
return currentY;
}
// Helper method to draw wrapped text
private float drawWrappedText(PDPageContentStream contentStream, PDFont font, float fontSize,
String text, float x, float y, float maxWidth) throws IOException {
contentStream.setFont(font, fontSize);
String[] lines = text.split("\n");
for (String line : lines) {
contentStream.beginText();
contentStream.newLineAtOffset(x, y);
contentStream.showText(line);
contentStream.endText();
y -= 12; // Line height
}
return y;
}
Key Correction:
The main change is in the font initialization:
// OLD (incorrect for PDFBox 3.x):
// PDFont fontBold = PDType1Font.HELVETICA_BOLD;
// PDFont fontNormal = PDType1Font.HELVETICA;
// NEW (correct for PDFBox 3.x):
PDFont fontBold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);
PDFont fontNormal = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
Required Imports:
Make sure you have these imports at the top of your class:
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
This should resolve the font initialization error you're encountering with PDFBox 3.x.