Search in sources :

Example 1 with Document

use of com.lowagie.text.Document in project Openfire by igniterealtime.

the class GraphServlet method writePDFContent.

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart[] charts, Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {
    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();
        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {
            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));
            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }
        document.close();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ServletOutputStream(javax.servlet.ServletOutputStream) Rectangle2D(java.awt.geom.Rectangle2D) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) PdfTemplate(com.lowagie.text.pdf.PdfTemplate) Date(java.util.Date) Paragraph(com.lowagie.text.Paragraph) Graphics2D(java.awt.Graphics2D) Statistic(org.jivesoftware.openfire.stats.Statistic) DocumentException(com.lowagie.text.DocumentException) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 2 with Document

use of com.lowagie.text.Document in project Openfire by igniterealtime.

the class ConversationUtils method buildPDFContent.

private ByteArrayOutputStream buildPDFContent(Conversation conversation, Map<String, Font> colorMap) {
    Font roomEvent = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));
    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener());
        document.open();
        Paragraph p = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.title", MonitoringConstants.NAME), FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
        document.add(p);
        document.add(Chunk.NEWLINE);
        ConversationInfo coninfo = new ConversationUtils().getConversationInfo(conversation.getConversationID(), false);
        String participantsDetail;
        if (coninfo.getAllParticipants() == null) {
            participantsDetail = coninfo.getParticipant1() + ", " + coninfo.getParticipant2();
        } else {
            participantsDetail = String.valueOf(coninfo.getAllParticipants().length);
        }
        Paragraph chapterTitle = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.participants", MonitoringConstants.NAME) + " " + participantsDetail, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(chapterTitle);
        Paragraph startDate = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.startdate", MonitoringConstants.NAME) + " " + coninfo.getDate(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(startDate);
        Paragraph duration = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.duration", MonitoringConstants.NAME) + " " + coninfo.getDuration(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(duration);
        Paragraph messageCount = new Paragraph(LocaleUtils.getLocalizedString("archive.search.pdf.messagecount", MonitoringConstants.NAME) + " " + conversation.getMessageCount(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(messageCount);
        document.add(Chunk.NEWLINE);
        Paragraph messageParagraph;
        for (ArchivedMessage message : conversation.getMessages()) {
            String time = JiveGlobals.formatTime(message.getSentDate());
            String from = message.getFromJID().getNode();
            if (conversation.getRoom() != null) {
                from = message.getToJID().getResource();
            }
            String body = message.getBody();
            String prefix;
            if (!message.isRoomEvent()) {
                prefix = "[" + time + "] " + from + ":  ";
                Font font = colorMap.get(message.getFromJID().toString());
                if (font == null) {
                    font = colorMap.get(message.getFromJID().toBareJID());
                }
                if (font == null) {
                    font = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.BOLD, Color.BLACK);
                }
                messageParagraph = new Paragraph(new Chunk(prefix, font));
            } else {
                prefix = "[" + time + "] ";
                messageParagraph = new Paragraph(new Chunk(prefix, roomEvent));
            }
            messageParagraph.add(body);
            messageParagraph.add(" ");
            document.add(messageParagraph);
        }
        document.close();
        return baos;
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage(), e);
        return null;
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) Color(java.awt.Color) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) Chunk(com.lowagie.text.Chunk) Font(com.lowagie.text.Font) Paragraph(com.lowagie.text.Paragraph) DocumentException(com.lowagie.text.DocumentException)

Example 3 with Document

use of com.lowagie.text.Document in project adempiere by adempiere.

the class SmjPdfReport method generate.

/**
	 * genera el PDF en un ByteArrayOutputStream ** Generate PDF Report into
	 * ByteArrayOutputStream
	 * 
	 * @return ByteArrayOutputStream
	 */
public ByteArrayOutputStream generate(LinkedList<ReportTO> dataReport, String nameTrx, String[] generalTitle, String clientName, String clientNIT, String periodName, String currencyName, MReportColumn[] m_columns, String codeFont, String city, Integer logoId) {
    baosPDF = new ByteArrayOutputStream();
    data = dataReport;
    String[] fontPar = codeFont.split("-");
    Integer lFont = Integer.parseInt(fontPar[2]);
    titleFont = FontFactory.getFont(fontPar[0], lFont + 5, Font.BOLDITALIC);
    titleTableFont = FontFactory.getFont(fontPar[0], lFont + 2, Font.BOLDITALIC);
    catFont = FontFactory.getFont(fontPar[0], lFont + 2, Font.BOLD);
    subFont = FontFactory.getFont(fontPar[0], lFont, Font.NORMAL);
    try {
        // izq-der-arrib
        document = new Document(PageSize.LETTER, 20, 20, 20, 40);
        writer = PdfWriter.getInstance(document, baosPDF);
        document.open();
        // metadata del documento
        document.addTitle(generalTitle[0]);
        document.addAuthor("SmartJSP S.A.S.");
        document.addCreator("SmartJSP S.A.S.");
        onOpenDocument(writer, document);
        onEndPage(writer, document);
        // //////////////////////////////////////////////////////////////////////////////////////
        // agrega el logo
        // add logo
        java.awt.Image img;
        if (logoId > 0) {
            MImage mimage = MImage.get(Env.getCtx(), logoId);
            byte[] imageData = mimage.getData();
            img = Toolkit.getDefaultToolkit().createImage(imageData);
        } else {
            // 48x15
            img = org.compiere.Adempiere.getImageLogoSmall(true);
        }
        com.lowagie.text.Image logo = com.lowagie.text.Image.getInstance(img, null);
        logo.scaleToFit(100, 30);
        document.add(logo);
        // Titulo General - general Title
        Paragraph genTitle = new Paragraph(dataNull(generalTitle[0]).toUpperCase(), titleFont);
        genTitle.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(genTitle);
        // empresa - Company
        Paragraph clitName = new Paragraph(dataNull(clientName).toUpperCase(), titleFont);
        clitName.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(clitName);
        // Ciudad - City
        Paragraph cliCity = new Paragraph(dataNull(city).toUpperCase(), titleFont);
        cliCity.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(cliCity);
        // NIT
        Paragraph cliNIT = new Paragraph(dataNull(clientNIT).toUpperCase(), titleFont);
        cliNIT.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(cliNIT);
        // periodo - Period
        String pn = "";
        if (generalTitle[1] != null && generalTitle[1].length() > 0) {
            pn = generalTitle[1] + " " + periodName;
        } else {
            pn = periodName;
        }
        if (generalTitle[2] != null && generalTitle[2].length() > 0) {
            pn = pn + " " + generalTitle[2];
        }
        Paragraph perName = new Paragraph(dataNull(pn).toUpperCase(), titleTableFont);
        perName.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(perName);
        // tipo moneda - currency
        Paragraph currency = new Paragraph(dataNull(currencyName), titleTableFont);
        currency.setAlignment(Paragraph.ALIGN_CENTER);
        addEmptyLine(currency, 2);
        document.add(currency);
        cols = m_columns.length + 2;
        float[] columnWidths = new float[cols];
        columnWidths[0] = 1f;
        columnWidths[1] = 3f;
        for (int i = 2; i < cols; i++) {
            columnWidths[i] = 1f;
        }
        table = new PdfPTable(columnWidths);
        // //Titulos de la tabla - Table titles
        // Nombre - name
        PdfPCell cellTitle = new PdfPCell(new Paragraph(Msg.translate(Env.getCtx(), "name").toUpperCase(), catFont));
        cellTitle.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
        cellTitle.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cellTitle);
        // Desripcion - description
        cellTitle = new PdfPCell(new Paragraph(Msg.translate(Env.getCtx(), "description").toUpperCase(), catFont));
        cellTitle.setHorizontalAlignment(Paragraph.ALIGN_LEFT);
        cellTitle.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cellTitle);
        // columnas de valores - Value Columns
        for (MReportColumn mcol : m_columns) {
            String colName = mcol.getName();
            cellTitle = new PdfPCell(new Paragraph(colName.toUpperCase(), catFont));
            cellTitle.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            cellTitle.setBackgroundColor(Color.LIGHT_GRAY);
            table.addCell(cellTitle);
        }
        //for columnas
        // TABLA DEL REPORTE - REPORT TABLE
        reportTable();
        document.add(table);
        // funciones que ponen el pie del porte - put footer
        onEndPage(writer, document);
        onCloseDocument(writer, document);
        document.close();
    } catch (Exception e) {
        System.out.println("SMpdfReport(generar)ERROR:: al crear el documento PDF");
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return baosPDF;
}
Also used : PdfPCell(com.lowagie.text.pdf.PdfPCell) MReportColumn(org.compiere.report.MReportColumn) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Paragraph(com.lowagie.text.Paragraph) MImage(org.compiere.model.MImage) PdfPTable(com.lowagie.text.pdf.PdfPTable)

Example 4 with Document

use of com.lowagie.text.Document in project adempiere by adempiere.

the class AEnv method mergePdf.

/**
     *
     * @param pdfList
     * @param outFile
     * @throws IOException
     * @throws DocumentException
     * @throws FileNotFoundException
     */
public static void mergePdf(List<File> pdfList, File outFile) throws IOException, DocumentException, FileNotFoundException {
    Document document = null;
    PdfWriter copy = null;
    for (File f : pdfList) {
        PdfReader reader = new PdfReader(f.getAbsolutePath());
        if (document == null) {
            document = new Document(reader.getPageSizeWithRotation(1));
            copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
            document.open();
        }
        int pages = reader.getNumberOfPages();
        PdfContentByte cb = copy.getDirectContent();
        for (int i = 1; i <= pages; i++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, i);
            cb.addTemplate(page, 0, 0);
        }
    }
    document.close();
}
Also used : PdfImportedPage(com.lowagie.text.pdf.PdfImportedPage) PdfWriter(com.lowagie.text.pdf.PdfWriter) FileOutputStream(java.io.FileOutputStream) PdfContentByte(com.lowagie.text.pdf.PdfContentByte) PdfReader(com.lowagie.text.pdf.PdfReader) Document(com.lowagie.text.Document) File(java.io.File)

Example 5 with Document

use of com.lowagie.text.Document in project dhis2-core by dhis2.

the class PdfFormController method getFormPdfProgramStage.

//--------------------------------------------------------------------------
// Program Stage
//--------------------------------------------------------------------------
@RequestMapping(value = "/programStage/{programStageUid}", method = RequestMethod.GET)
public void getFormPdfProgramStage(@PathVariable String programStageUid, HttpServletRequest request, HttpServletResponse response, OutputStream out) throws Exception {
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    PdfFormFontSettings pdfFormFontSettings = new PdfFormFontSettings();
    PdfDataEntryFormUtil.setDefaultFooterOnDocument(document, request.getServerName(), pdfFormFontSettings.getFont(PdfFormFontSettings.FONTTYPE_FOOTER));
    pdfDataEntryFormService.generatePDFDataEntryForm(document, writer, programStageUid, PdfDataEntryFormUtil.DATATYPE_PROGRAMSTAGE, PdfDataEntryFormUtil.getDefaultPageSize(PdfDataEntryFormUtil.DATATYPE_PROGRAMSTAGE), pdfFormFontSettings, i18nManager.getI18nFormat());
    String fileName = programStageService.getProgramStage(programStageUid).getName() + " " + DateUtils.getMediumDateString() + ".pdf";
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_PDF, CacheStrategy.NO_CACHE, fileName, true);
    response.setContentLength(baos.size());
    baos.writeTo(out);
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) PdfFormFontSettings(org.hisp.dhis.dxf2.pdfform.PdfFormFontSettings) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Document (com.lowagie.text.Document)36 DocumentException (com.lowagie.text.DocumentException)20 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 PdfWriter (com.lowagie.text.pdf.PdfWriter)13 Paragraph (com.lowagie.text.Paragraph)12 IOException (java.io.IOException)12 Rectangle (com.lowagie.text.Rectangle)10 PdfContentByte (com.lowagie.text.pdf.PdfContentByte)9 FileOutputStream (java.io.FileOutputStream)9 Color (java.awt.Color)8 DefaultFontMapper (com.lowagie.text.pdf.DefaultFontMapper)6 PdfImportedPage (com.lowagie.text.pdf.PdfImportedPage)5 File (java.io.File)5 DocWriter (com.lowagie.text.DocWriter)4 Phrase (com.lowagie.text.Phrase)4 PdfPCell (com.lowagie.text.pdf.PdfPCell)4 PdfPTable (com.lowagie.text.pdf.PdfPTable)4 PdfReader (com.lowagie.text.pdf.PdfReader)4 Graphics2D (java.awt.Graphics2D)4 OutputStream (java.io.OutputStream)4