Example usage for com.lowagie.text FontFactory getFont

List of usage examples for com.lowagie.text FontFactory getFont

Introduction

In this page you can find the example usage for com.lowagie.text FontFactory getFont.

Prototype


public static Font getFont(String fontname, float size, int style, Color color) 

Source Link

Document

Constructs a Font-object.

Usage

From source file:org.jivesoftware.openfire.archive.ConversationUtils.java

License:Open Source License

private ByteArrayOutputStream buildPDFContent(Conversation conversation, Map<String, Font> colorMap) {
    Font roomEvent = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));

    try {//from  w  w  w  .j  a v a 2s  .  co m
        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;
    }
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

License:Open Source License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 * @return/*w w  w .j av  a2 s.c  o m*/
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark()); // add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.coeus.s2sgen.impl.print.S2SPrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 *//*from   w ww.ja  va  2s.  com*/
protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = Calendar.getInstance();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new Document(reader.getPageSizeWithRotation(1)) : new Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new S2SException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList/*from   w  w w . jav  a 2 s .  com*/
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.netxilia.server.rest.pdf.SheetPdfProvider.java

License:Open Source License

@Override
public void writeTo(SheetFullName sheetName, Class<?> clazz, Type type, Annotation[] ann, MediaType mediaType,
        MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException {

    if (sheetName == null) {
        return;//from   www.  j  av  a  2  s  . c o m
    }

    /**
     * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the
     * visible table into the PDF
     */
    Table tablePDF;

    /**
     * The default font used in the document.
     */
    Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new Color(0, 0, 0));
    ISheet summarySheet = null;
    ISheet sheet = null;
    try {
        sheet = workbookProcessor.getWorkbook(sheetName.getWorkbookId()).getSheet(sheetName.getSheetName());
        try {
            // get the corresponding summary sheet
            SheetFullName summarySheetName = SheetFullName.summarySheetName(sheetName,
                    userService.getCurrentUser());
            summarySheet = workbookProcessor.getWorkbook(summarySheetName.getWorkbookId())
                    .getSheet(summarySheetName.getSheetName());

        } catch (Exception e) {
            // no summary sheet - go without one
        }

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        HeaderFooter footer = new HeaderFooter(new Phrase("", smallFont), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        PdfWriter.getInstance(document, out);

        // Fill the virtual PDF table with the necessary data
        // Initialize the table with the appropriate number of columns
        tablePDF = initTable(sheet);
        // take tha maximum numbers of columns
        int columnCount = sheet.getDimensions().getNonBlocking().getColumnCount();
        if (summarySheet != null) {
            columnCount = Math.max(columnCount, summarySheet.getDimensions().getNonBlocking().getColumnCount());
        }
        generateHeaders(sheet, tablePDF, smallFont, columnCount);

        tablePDF.endHeaders();
        generateRows(sheet, false, tablePDF, smallFont, columnCount);
        if (summarySheet != null) {
            generateRows(summarySheet, true, tablePDF, smallFont, columnCount);
        }

        document.open();
        document.setFooter(footer);
        document.add(tablePDF);
        document.close();

        out.flush();
        out.close();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

@Override
public Blob signPDF(Blob pdfBlob, DocumentModel user, String keyPassword, String reason)
        throws ClientException {
    CertService certService = Framework.getLocalService(CertService.class);
    CUserService cUserService = Framework.getLocalService(CUserService.class);
    try {/*from www  .j  ava  2 s  .  co m*/
        File outputFile = File.createTempFile("signed-", ".pdf");
        Blob blob = Blobs.createBlob(outputFile, MIME_TYPE_PDF);
        Framework.trackFile(outputFile, blob);

        PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
        List<X509Certificate> pdfCertificates = getCertificates(pdfReader);

        // allows for multiple signatures
        PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, new FileOutputStream(outputFile), '\0',
                null, true);

        PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
        String userID = (String) user.getPropertyValue("user:username");
        AliasWrapper alias = new AliasWrapper(userID);
        KeyStore keystore = cUserService.getUserKeystore(userID, keyPassword);
        Certificate certificate = certService.getCertificate(keystore, alias.getId(AliasType.CERT));
        KeyPair keyPair = certService.getKeyPair(keystore, alias.getId(AliasType.KEY),
                alias.getId(AliasType.CERT), keyPassword);

        if (certificatePresentInPDF(certificate, pdfCertificates)) {
            X509Certificate userX509Certificate = (X509Certificate) certificate;
            String message = ALREADY_SIGNED_BY + userX509Certificate.getSubjectDN();
            log.debug(message);
            throw new AlreadySignedException(message);
        }

        List<Certificate> certificates = new ArrayList<Certificate>();
        certificates.add(certificate);

        Certificate[] certChain = certificates.toArray(new Certificate[0]);
        pdfSignatureAppearance.setCrypto(keyPair.getPrivate(), certChain, null,
                PdfSignatureAppearance.SELF_SIGNED);
        if (StringUtils.isBlank(reason)) {
            reason = getSigningReason();
        }
        pdfSignatureAppearance.setReason(reason);
        pdfSignatureAppearance.setAcro6Layers(true);
        Font layer2Font = FontFactory.getFont(FontFactory.TIMES, getSignatureLayout().getTextSize(),
                Font.NORMAL, new Color(0x00, 0x00, 0x00));
        pdfSignatureAppearance.setLayer2Font(layer2Font);
        pdfSignatureAppearance.setRender(PdfSignatureAppearance.SignatureRenderDescription);

        pdfSignatureAppearance.setVisibleSignature(getNextCertificatePosition(pdfReader, pdfCertificates), 1,
                null);

        pdfStamper.close(); // closes the file

        log.debug("File " + outputFile.getAbsolutePath() + " created and signed with " + reason);

        return blob;
    } catch (IOException e) {
        throw new SignException(e);
    } catch (DocumentException e) {
        // iText PDF stamping
        throw new SignException(e);
    } catch (IllegalArgumentException e) {
        if (String.valueOf(e.getMessage()).contains("PdfReader not opened with owner password")) {
            // iText PDF reading
            throw new SignException("PDF is password-protected");
        }
        throw new SignException(e);
    }
}

From source file:org.sonar.report.pdf.Header.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {//w  w w  .  j a v a  2  s.c om
        Image logoImage = Image.getInstance(logo);
        Rectangle page = document.getPageSize();
        PdfPTable head = new PdfPTable(4);
        head.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        head.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
        head.addCell(logoImage);
        Phrase projectName = new Phrase(project.getName(),
                FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY));
        Phrase phrase = new Phrase("Sonar PDF Report",
                FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY));
        head.getDefaultCell().setColspan(2);
        head.addCell(phrase);
        head.getDefaultCell().setColspan(1);
        head.addCell(projectName);
        head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - 20, writer.getDirectContent());
        head.setSpacingAfter(10);
    } catch (BadElementException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.sonarqube.report.extendedpdf.ExtendedHeader.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    String pageTemplate = "/templates/page.pdf";
    try {//from ww w. j a va  2 s.  c  o  m
        PdfContentByte cb = writer.getDirectContentUnder();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(pageTemplate));
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        cb.addTemplate(page, 0, 0);

        Font font = FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY);
        Rectangle pageSize = document.getPageSize();
        PdfPTable head = new PdfPTable(1);
        head.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        head.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
        head.getDefaultCell().setBorder(0);
        Phrase projectName = new Phrase(project.getName(), font);
        head.addCell(projectName);
        head.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(), pageSize.getHeight() - 15,
                writer.getDirectContent());
        head.setSpacingAfter(10);

        PdfPTable foot = new PdfPTable(1);
        foot.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        foot.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        foot.getDefaultCell().setBorder(0);
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase(df.format(project.getMeasures().getDate()), font);
        foot.addCell(projectAnalysisDate);
        foot.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        foot.writeSelectedRows(0, -1, document.leftMargin(), 20, writer.getDirectContent());
        foot.setSpacingBefore(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + pageTemplate);
        e.printStackTrace();
    }
}

From source file:org.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter)
        throws org.dom4j.DocumentException, ReportException {
    String frontPageTemplate = "/templates/frontpage.pdf";
    try {/*from w w  w  .  j  av a 2s  .co  m*/
        PdfContentByte cb = frontPageWriter.getDirectContent();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(frontPageTemplate));
        PdfImportedPage page = frontPageWriter.getImportedPage(reader, 1);
        frontPageDocument.newPage();
        cb.addTemplate(page, 0, 0);

        Project project = getProject();

        Rectangle pageSize = frontPageDocument.getPageSize();
        PdfPTable projectInfo = new PdfPTable(1);
        projectInfo.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        projectInfo.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        projectInfo.getDefaultCell().setBorder(Rectangle.BOTTOM);
        projectInfo.getDefaultCell().setPaddingBottom(10);
        projectInfo.getDefaultCell().setBorderColor(Color.GRAY);
        Font font = FontFactory.getFont(FontFactory.COURIER, 18, Font.NORMAL, Color.LIGHT_GRAY);

        Phrase projectName = new Phrase("Project: " + project.getName(), font);
        projectInfo.addCell(projectName);

        Phrase projectVersion = new Phrase("Version: " + project.getMeasures().getVersion(), font);
        projectInfo.addCell(projectVersion);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase("Analysis Date: " + df.format(project.getMeasures().getDate()),
                font);
        projectInfo.addCell(projectAnalysisDate);

        projectInfo.setTotalWidth(
                pageSize.getWidth() - frontPageDocument.leftMargin() * 2 - frontPageDocument.rightMargin() * 2);
        projectInfo.writeSelectedRows(0, -1, frontPageDocument.leftMargin(), pageSize.getHeight() - 575,
                frontPageWriter.getDirectContent());
        projectInfo.setSpacingAfter(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + frontPageTemplate);
        e.printStackTrace();
    }
}

From source file:questions.fonts.EncodingFont.java

public static void main(String[] args) {
    Document document = new Document();
    try {/*from  w w w  .  jav  a 2 s  .c  o m*/
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        String cp1252String, cp1250String, cp1253String;
        Font cp1252Font, cp1250Font, cp1253Font;

        document.add(new Paragraph("The importance of using the right encoding!"));
        document.add(new Paragraph("CORRECT:"));
        // CP1252
        cp1252String = "CP1252: 'Un long dimanche de fian\u00e7ailles'";
        cp1252Font = FontFactory.getFont("c:/windows/fonts/arial.ttf", "Cp1252", BaseFont.EMBEDDED, 12);
        document.add(new Paragraph(cp1252String, cp1252Font));
        // CP1250
        cp1250String = "CP1250: 'Nikogar\u0161nja zemlja'";
        cp1250Font = FontFactory.getFont("c:/windows/fonts/arial.ttf", "Cp1250", BaseFont.EMBEDDED, 12);
        document.add(new Paragraph(cp1250String, cp1250Font));
        // CP1253
        cp1253String = "CP1253: '\u039D\u03cd\u03c6\u03b5\u03c2'";
        cp1253Font = FontFactory.getFont("c:/windows/fonts/arial.ttf", "Cp1253", BaseFont.EMBEDDED, 12);
        document.add(new Paragraph(cp1253String, cp1253Font));
        // The right String with the wrong encoding
        document.add(new Paragraph("POSSIBLY WRONG:"));
        document.add(new Paragraph(cp1252String + " (1250)", cp1250Font));
        document.add(new Paragraph(cp1252String + " (1253)", cp1253Font));
        document.add(new Paragraph(cp1250String + " (1252)", cp1252Font));
        document.add(new Paragraph(cp1250String + " (1253)", cp1253Font));
        document.add(new Paragraph(cp1253String + " (1252)", cp1252Font));
        document.add(new Paragraph(cp1253String + " (1250)", cp1250Font));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();
}