package at.gv.egiz.simpleSigning.helper; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import at.gv.egiz.simpleSigning.ErrorSignature; public class PDFHelper { private static final Logger logger = LoggerFactory .getLogger(PDFHelper.class); // private static byte[] createPDFiText(String text) { // try { // Document document = new Document(PageSize.A4, 36, 72, 108, 180); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // PdfWriter.getInstance(document,baos); // document.open(); // document.add(new Paragraph(text)); // System.out.println("Text is inserted into pdf file"); // document.close(); // baos.close(); // return baos.toByteArray(); // } catch(Throwable e) { // logger.error("Failed to create PDF", e); // } // return null; // } private static byte[] createPDFPdfBox(String text) { try { // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage( page ); // Create a new font object selecting one of the PDF base fonts PDFont font = PDType1Font.TIMES_BOLD; // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(document, page); // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World" contentStream.beginText(); contentStream.setFont( font, 12 ); contentStream.newLineAtOffset(100, 700); contentStream.showText(text); contentStream.endText(); // Make sure that the content stream is closed: contentStream.close(); // Save the result into byte array ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.save(byteArrayOutputStream); document.close(); return byteArrayOutputStream.toByteArray(); } catch (Exception e) { logger.error("Failed to create PDF", e); return null; } } public static byte[] createPDFDocument(String text) { return createPDFPdfBox(text); } public static void toError(HttpServletRequest req, HttpServletResponse resp, String error, String cause) throws ServletException, IOException { req.setAttribute(ErrorSignature.PARAM_ERROR, error); req.setAttribute(ErrorSignature.PARAM_CAUSE, cause); req.getRequestDispatcher("Error").forward(req, resp); } }