best way to generate XLSX and convert to PDF for mailing

57 Views Asked by At

I am working on a report that will be run in my hosted service. Currently using Java, Spring, etc. I need to take a list of patient data and parse it into a structure such as this:

enter image description here

So it seems logical that I would recreated it as a spreadsheet since it appears to be rows & columns. Each patient will have its own worksheet in the workbook. I see there are lots of good XLSX libraries (fastexcel and apache poi) so I am not worried about that. My concern is converting it to a PDF. I looked at Apache PDFBox but I am really struggling to convert my xlsx into a PDF file that will be emailed as an attachment.

I also found some examples that use iText to convert - but I can't afford that solution or release my source code.

Has anyone got experience with this and can offer some advice? Am I overly complicating this or trying the wrong tools? I have spent two days trying to get this conversion right and just not having any success.

Here is where I stopped:

public PDDocument convertExcelToPdf(Workbook wb) {

PDDocument pdfDocument = new PDDocument();
try {
    Iterator<Sheet> sheetIterator = wb.iterator();

    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        PDPage page = new PDPage(PDRectangle.A4);
        pdfDocument.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(pdfDocument, page);
        for (Row row : sheet) {
            for (Cell cell : row) {
                // Write cell data to PDF content stream
                contentStream.beginText();
                contentStream.newLineAtOffset(100, 700);  
                contentStream.setFont(FontName.COURIER); <== do I have to set the font & borders on every cell that was already defined in the spreadsheet?
                contentStream.showText(cell.getStringCellValue());
                contentStream.endText();
            }
        }

        // Save the PDF document
        contentStream.close();
    }
    pdfDocument.save(new FileOutputStream(new File("MAR.pdf")));
    pdfDocument.close();
    wb.close();
    return pdfDocument;
} catch (IOException e) {
    logger.error("Unable to parse Workbook", e.getMessage());
    return pdfDocument;
}

}

0

There are 0 best solutions below