I’m trying to generate PDFs from scratch using Spring. After some research, I’ve found a number of libraries such as iText, PDFBox, Apose, Jasper, etc. Looking at org.springframework.web.servlet.view.document.AbstractPdfView
, I quote:
Spring offers ways to return output other than HTML, including PDF and Excel spreadsheets.
public class PdfWordList extends AbstractPdfView {
protected void buildPdfDocument(Map<String, Object> model, Document doc, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> words = (List<String>) model.get("wordList");
for (String word : words) {
doc.add(new Paragraph(word));
}
}
}
Can we generate PDFs report from scratch using Spring AbstractPdfView
, or do I need to use Jasper to create templates and integrate it with Spring boot?
1
In my project I had followed the approach to convert HTML of the document to into PDF while retaining all the CSS, since modelling PDF using Java can be quite cumbersome. You can prepare HTML server side or can accept html payload request from your front-end. I was able to make in work using itextpdf:html2pdf
.
Add this dependency in your project.
implementation 'com.itextpdf:html2pdf:3.0.2'
Java Code :
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HtmlToPdfConvertor {
public static void main(String[] args) throws IOException {
String htmlFileName = index.html;
String outputPdfFileName = res.pdf;
final String htmlString = Files.readAllBytes(Path.of(htmlFileName));
try (FileOutputStream fos = new FileOutputStream(outputPdfFileName)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument doc = new PdfDocument(new PdfWriter(baos));
doc.setDefaultPageSize(PageSize.A4);
ConverterProperties props = new ConverterProperties();
HtmlConverter.convertToPdf(html, doc, props);
fos.write(baos.toByteArray());
}
}
}