/* * Copyright (C) 2022 Alessandro Iezzi * * This file is part of Simply Reports. * * Simply Reports is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Simply Reports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Simply Reports. If not, see . */ package it.alessandroiezzi.simplyreports.pdf; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.pdf.PdfWriter; import lombok.Getter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class PDFDocument { private final Document document; private final PdfWriter writer; private final List elements = new ArrayList<>(); private final @Getter String fileDestination; public PDFDocument(String fileDestination) throws IOException, DocumentException { this.fileDestination = fileDestination; document = new Document(); writer = PdfWriter.getInstance(document, Files.newOutputStream(Paths.get(fileDestination))); } private void openDocument() { if (document.isOpen()) return; document.open(); } private void add(Element element) { elements.add(element); } public void add(PDFTable table) { elements.add(table); } public void saveToFile() { try { openDocument(); for (Object element : elements) { if (element instanceof Element) { document.add((Element) element); } else if (element instanceof PDFTable) { document.add(((PDFTable) element).generate(writer)); } } if (document.isOpen()) document.close(); } catch (DocumentException e) { throw new RuntimeException(e); } } }