PDFs konkateniert als HttpResponse zurückgeben

Um irgendwas mit PDF zu machen, bietet sich die Bibliothek iText an. Die API finde ich persönlich nicht sonderlich schön, aber man hat ja keine Wahl…

Hier ein Snippet, wie man ganze PDF-Dokumente konkateniert und dann als ein PDF ausgibt. Es gibt sicherlich schönere Lösungen. Comments sind immer willkommen. Nachteilig ist hier vor allem die Benutzung von byte[]. Je nach konkretem Anwendungsfall sollte man besser auf Streams umsteigen.

public doGet(HttpServleRequest request, HttpServletResponse response){

byte[][] files = ...;

String fileName = "myfile.pdf";

response.setHeader("Pragma", "public");
response.setHeader("Cache-control", "must-revalidate");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "filename=" + fileName);

Document document = new Document();

PdfCopy copy = new PdfCopy(document, response.getOutputStream());
document.open();
for (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
int pageNum = reader.getNumberOfPages();
for (int j = 1; j <= pageNum; j++) {
copy.addPage(copy.getImportedPage(reader, j));
}
}
document.close();

}

2 thoughts on “PDFs konkateniert als HttpResponse zurückgeben”

  1. Don’t worry; iText evolved organically, so we are aware of the fact that the API is a tad quirky in some areas, but overall we’re quite happy with iText 😉

Comments are closed.