Search code examples
javaitextspring-roo

java generate PDF in separate class but return from controller


I'm trying to add a PDF generator to my website. Everything works fine as far as the generator in the controller

ConsumerController.java:

public String downloadPDF(@PathVariable("id") Long id, @PathVariable("transaction") Long transaction, Model uiModel, HttpServletRequest httpServletRequest, HttpServletResponse response) {
Document document = new Document();
try{
    response.setContentType("application/pdf");
    PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    document.add(new Paragraph("Hello Kiran"));
document.add(new Paragraph("Hello" + id));
document.add(new Paragraph("For"+ transaction));
    document.add(new Paragraph(new Date().toString()));
}catch(Exception e){
    e.printStackTrace();
}
document.close();
return null;
}

this is what i have at the moment and this is exactly how i want it to work, but the one i would like to add would be better off in its own class (code below).

PDFGenerator.java:

public void generatorPDF() throws Exception{
    Document d = new Document();
    try{
    PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream("CodeOfDoom.pdf"));
    d.open();
    for(int i=0; i<10; i++){
            PdfPTable table = generateLineItemTable(_order.getLineItems());
    PdfPTable headerTable= generateHeaderTable(_order.getCustomer());
    addBarcode(writer,headerTable);
    //add customer barcode to the header
    d.add(headerTable);
    d.add(table);
    Paragraph p = new Paragraph("\n\nFor more, please visit ");
    Anchor anchor = new Anchor("www.codeofdoom.com/wordpress");

    p.add(anchor);
    d.add(p);
            d.newPage();
            }
    d.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

so far with anything that i have tried, the PDF writer seems to be the issue, because I'm not sure how to go about adding the document to the writer from a separate class


Solution

  • In the first instance, you're creating the PDF and writing it directly to the response stream. In the second class, you are writing it to a file.

    If you want to create the PDF in a different class, one solution would be to pass the output stream into the constructor of the class. If you don't want to pass a reference to the output stream, you could create the PDF in memory by writing to a ByteArrayOutputStream and then return the generated array of bytes. With that approach, you could then write the generated PDF bytes back to the response stream. This approach assumes your PDF is small enough to fit into memory, though.