Example usage for com.lowagie.text.pdf BaseFont EMBEDDED

List of usage examples for com.lowagie.text.pdf BaseFont EMBEDDED

Introduction

In this page you can find the example usage for com.lowagie.text.pdf BaseFont EMBEDDED.

Prototype

boolean EMBEDDED

To view the source code for com.lowagie.text.pdf BaseFont EMBEDDED.

Click Source Link

Document

if the font has to be embedded

Usage

From source file:mx.dr.util.report.impl.PdfService.java

License:Open Source License

/**
* write a label in pdf document./*from ww  w .j  a va2 s.c  om*/
* <br/>
* escribe una etiqueta en el documento pdf.
* @param doc pdf document / documento pdf.
* @param dto object that encompasses the values of the labels to be placed in the document / objeto que engloba los valores de las etiquetas que se colocaran en el documento.
* @param offset jump on the Y axis to be given before placing the tag in the document / salto en el eje Y que se dara antes de colocar la etiqueta en el documento.
* @param table container table if applicable / contenedor de tabla si es que aplica.
* @throws Exception If an error occurs / si ocurre algun error.
*/
public void estampaEtiqueta(Document doc, Object dto, Float offset, PdfPTable table) throws Exception {
    List<Field> fields = new ArrayList<Field>();

    for (Field m : dto.getClass().getDeclaredFields()) {
        m.setAccessible(true);
        if (m.getAnnotation(DRPdfLabel.class) != null) {
            fields.add(m);
        }
    }
    Collections.sort(fields, new Comparator<Field>() {

        public int compare(Field o1, Field o2) {
            DRPdfLabel etiqueta1 = o1.getAnnotation(DRPdfLabel.class);
            DRPdfLabel etiqueta2 = o2.getAnnotation(DRPdfLabel.class);
            String uno = int2String(etiqueta1.y()) + "." + int2String(etiqueta1.order());
            String dos = int2String(etiqueta2.y()) + "." + int2String(etiqueta2.order());
            return uno.compareTo(dos);

        }

        private String int2String(int num) {
            if (num < 10) {
                return "0" + num;
            } else {
                return String.valueOf(num);
            }
        }
    });
    DRPdfLabel etiqueta;
    DRPdfTable etiquetaTabla;
    int lineaActual = 0;
    Paragraph pantagram = null;
    StringBuffer sb = null;
    Font font;
    Object valor;
    String label;
    DRPdfImage img;
    int residuo;
    int adicional = 0;
    for (Field m : fields) {
        etiqueta = m.getAnnotation(DRPdfLabel.class);
        img = m.getAnnotation(DRPdfImage.class);
        valor = m.get(dto);
        if (valor != null && valor instanceof List) {
            etiquetaTabla = m.getAnnotation(DRPdfTable.class);
            PdfPTable tableDance = null;
            if (etiquetaTabla != null) {
                tableDance = new PdfPTable(etiquetaTabla.colsPercentage());
                tableDance.setSpacingBefore(etiqueta.offset());
                for (String c : etiquetaTabla.columnLabels()) {
                    tableDance.addCell(c);
                }
            }
            if (pantagram != null) {
                doc.add(pantagram);
                pantagram = null;
            }
            for (int i = 0; i < ((List) valor).size(); i++) {
                if (i == 0 && etiqueta.offset() > 0) {
                    estampaEtiqueta(doc, ((List) valor).get(i), etiqueta.offset(), tableDance);
                } else {
                    estampaEtiqueta(doc, ((List) valor).get(i), null, tableDance);
                }
            }
            if (etiquetaTabla != null) {
                doc.add(tableDance);
            }
        } else if (img != null) {
            /* File file = new File(IMGDIR + valor);
            FileInputStream inImg = new FileInputStream(file);
            byte[] b=new byte[(int)file.length()];
            inImg.read(b);*/

            Image ima = Image.getInstance(IMGDIR + valor);

            //System.out.println(ima.getPlainWidth());
            ima.scaleAbsoluteWidth(img.width());
            //System.out.println(ima.getScaledWidth());
            ima.scaleAbsoluteHeight(ima.getScaledWidth());
            ima.setAlignment(img.style());
            ima.setAbsolutePosition(img.x(), img.y());
            doc.add(ima);

        } else if (table != null) {

            PdfPCell cerda = null;

            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;
            DRPdfColumn col = m.getAnnotation(DRPdfColumn.class);
            if (col != null) {
                cerda = new PdfPCell(new Paragraph(label));
                cerda.setColspan(col.colspan());
                table.addCell(cerda);
            } else {
                table.addCell(label);
            }

        } else {
            if (lineaActual < etiqueta.y()) {
                if (pantagram != null) {
                    doc.add(pantagram);
                }
                if (offset == null || etiqueta.y() > 1) {
                    if (etiqueta.offset() > 0) {
                        pantagram = new Paragraph(etiqueta.offset());
                    } else {
                        pantagram = new Paragraph();
                    }
                } else {
                    pantagram = new Paragraph(offset);
                }
                lineaActual = etiqueta.y();
            }

            if (etiqueta.wspacesBefore() > 0) {
                sb = new StringBuffer("");
                fillEmpty(etiqueta.wspacesBefore(), sb);
                font = new Font(Font.COURIER, 12);
                pantagram.add(new Chunk(sb.toString(), font));
            }
            sb = new StringBuffer("");
            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;

            if (etiqueta.font().equals(BaseFont.COURIER)) {
                font = new Font(Font.COURIER, etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = 0;
            } else {
                font = FontFactory.getFont(TTFDIR + etiqueta.font(), BaseFont.CP1252, BaseFont.EMBEDDED,
                        etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = label.equals("") ? (residuo / 2) + 1 : 0;
            }

            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.DER) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            sb.append(label);
            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.IZQ) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            pantagram.add(new Chunk(sb.toString(), font));
        }
    }
    if (pantagram != null) {
        doc.add(pantagram);
    }

}

From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java

License:Open Source License

public void buildBook(List<File> inputFileList, File outputFile) {

    try {//from   w w w.j  a  v  a2 s  .c  o  m

        float pageWidth = getConfig().getPageWidth();
        float pageHeight = getConfig().getPageHeight();

        // Create new Document

        /*
        float marginLeft = 36;
        float marginRight = 36;
        float marginTop = 36;
        float marginBottom = 36;
        */

        if (isVerboseEnabled()) {
            verbose("Building output PDF file " + outputFile);
        }

        // TableOfContents toc = new TableOfContents();

        ProgressMonitor progressMonitor = getConfig().getProgressMonitor();
        TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener();

        Document outputDocument = new Document(getConfig().getPageSize());
        // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom );

        PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile));

        // TODO - review PDF page event forwarder
        PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger();
        pdfWriter.setPageEvent(pdfPageEventLogger);

        outputDocument.open();

        String metaTitle = getConfig().getMetaTitle();
        if (!StringUtils.isEmpty(metaTitle)) {
            outputDocument.addTitle(metaTitle);
        }
        String metaAuthor = getConfig().getMetaAuthor();
        if (!StringUtils.isEmpty(metaAuthor)) {
            outputDocument.addAuthor(metaAuthor);
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        // Loop through and pull pages
        int outputPageCount = 0;
        int currentSourceFileIndex = 0;
        int maxSourceFileIndex = inputFileList.size();

        // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED );
        BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250,
                BaseFont.EMBEDDED);
        if (isVerboseEnabled()) {
            verbose("Using page label font " + pageLabelFont);
        }

        if (isVerboseEnabled()) {
            verbose("Assembling pages using n-up " + getConfig().getNup());
        }

        for (File sourceFile : inputFileList) {

            currentSourceFileIndex++;

            // TODO - refactor current file PDF page processing to another method
            // TODO - handle failover to ensure processing continues ???

            if (sourceFile.isFile()) {

                if (isVerboseEnabled()) {
                    verbose("Reading source PDF file " + sourceFile);
                }

                int sourcePageIndex = 0;

                PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath());
                PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader);
                if (isVerboseEnabled()) {
                    verbose("PDF reader is " + sourcePdfReader);
                    verbose("PDF reader helper is " + sourcePdfReaderHelper);
                }

                String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName());
                String currentSourcePdfAuthor = getSystemUserName();
                if (isVerboseEnabled()) {
                    verbose("PDF title is " + currentSourcePdfTitle);
                    verbose("PDF author is " + currentSourcePdfAuthor);
                }

                currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle);
                currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor);
                if (isVerboseEnabled()) {
                    verbose("PDF info title is " + currentSourcePdfTitle);
                    verbose("PDF info author is " + currentSourcePdfAuthor);
                }

                boolean firstPageOfCurrentSource = true;

                int maxSourcePages = sourcePdfReader.getNumberOfPages();
                if (isVerboseEnabled()) {
                    verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile);
                }

                // process all pages from source doc
                while (sourcePageIndex < maxSourcePages) {

                    // add new page to current document
                    outputDocument.newPage();

                    outputPageCount++;
                    if (isVerboseEnabled()) {
                        verbose("Building output PDF page " + outputPageCount + " ...");
                    }

                    // add first page of current source to TOC listener
                    if (firstPageOfCurrentSource) {
                        int currentPageIndex = outputPageCount;
                        if (tocRowChangeListener != null) {
                            TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex);
                            tocRowChangeListener.addTocRow(tocEntry);
                            if (isVerboseEnabled()) {
                                verbose("Added TOC entry " + tocEntry + " to listener");
                            }
                        }
                        firstPageOfCurrentSource = false;
                    }

                    // extract first page from source document
                    sourcePageIndex++;
                    if (isVerboseEnabled()) {
                        verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                + " from source to output");
                    }
                    PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);

                    // n-up is 1
                    if (config.getNup() == 1) {
                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        // TODO - calculate scaling/transform based on page rect and template rect
                        float p1a = 0.65f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.65f;
                        float p1e = 20;
                        float p1f = 160;
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // n-up is 2 (default)
                    } else {

                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        float p1a = 0.5f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.5f;
                        float p1e = (125);
                        float p1f = ((pageWidth / 2) + 120 + 20);
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // extract second page from source document ?
                        PdfImportedPage page2 = null;
                        if (sourcePageIndex < maxSourcePages) {
                            sourcePageIndex++;
                            if (isVerboseEnabled()) {
                                verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                        + " from source to output");
                            }
                            page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);
                        }

                        // add second page to bottom half of current page
                        if (page2 != null) {
                            // TODO - review magic transformation matrix numbers and offsets
                            float p2a = 0.5f;
                            float p2b = 0;
                            float p2c = 0;
                            float p2d = 0.5f;
                            float p2e = 125;
                            float p2f = 120;
                            pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f);
                        }
                    }

                    /*
                    // add first page to top half of current page
                    // TODO - review magic transformation matrix numbers and offsets
                    float p1a = 0.5f;
                    float p1b = 0;
                    float p1c = 0;
                    float p1d = 0.5f;
                    float p1e = (125);
                    float p1f = ((pageWidth / 2) + 120 + 20);
                    pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f );
                            
                    // add second page to bottom half of current page
                    if (page2 != null) {
                       // TODO - review magic transformation matrix numbers and offsets
                       float p2a = 0.5f; 
                       float p2b = 0;
                       float p2c = 0;
                       float p2d = 0.5f;
                       float p2e = 125;
                       float p2f = 120;
                       pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f );
                    }
                    */

                    // Add current page number to page footer
                    String pageCountLabel = "Page " + outputPageCount;
                    pdfContent.beginText();
                    pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE);
                    pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40,
                            0);
                    pdfContent.endText();
                }

                if (isVerboseEnabled()) {
                    verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file "
                            + sourceFile);
                }

                // update progress
                if (isVerboseEnabled()) {
                    if (progressMonitor != null) {
                        int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex,
                                maxSourceFileIndex);
                        progressMonitor.setProgressPercentage(fileProgressPercentage);
                    }
                }
            }
        }

        // close document
        outputDocument.close();

        if (isVerboseEnabled()) {
            verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)");
        }

        // TODO - output ODT page stats summary

    } catch (Exception e) {

        String msg = "Error building PDF book: " + e.getMessage();
        e.printStackTrace(System.err);
        System.err.println(msg);

    }

}

From source file:net.sf.jsignpdf.utils.FontUtils.java

License:Mozilla Public License

/**
 * Returns BaseFont for text of visible signature;
 * //w  w  w. ja  va2s  .c om
 * @return
 */
public static synchronized BaseFont getL2BaseFont() {
    if (l2baseFont == null) {
        final ConfigProvider conf = ConfigProvider.getInstance();
        try {
            final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream();
            String fontPath = conf.getNotEmptyProperty("font.path", null);
            String fontName;
            String fontEncoding;
            InputStream tmpIs;
            if (fontPath != null) {
                fontName = conf.getNotEmptyProperty("font.name", null);
                if (fontName == null) {
                    fontName = new File(fontPath).getName();
                }
                fontEncoding = conf.getNotEmptyProperty("font.encoding", null);
                if (fontEncoding == null) {
                    fontEncoding = BaseFont.WINANSI;
                }
                tmpIs = new FileInputStream(fontPath);
            } else {
                fontName = Constants.L2TEXT_FONT_NAME;
                fontEncoding = BaseFont.IDENTITY_H;
                tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH);
            }
            IOUtils.copy(tmpIs, tmpBaos);
            tmpIs.close();
            tmpBaos.close();
            l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED,
                    tmpBaos.toByteArray(), null);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            } catch (Exception ex) {
                // where is the problem, dear Watson?
            }
        }
    }
    return l2baseFont;
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * //from www  . j  a va  2 s  .c  o  m
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.areasy.common.doclet.document.Fonts.java

License:Open Source License

public static Font getFont(int faceType, int style, int size) {
    Font font = null;//from  w  w  w  .  j  av a2s  .c om
    String lookup = String.valueOf(faceType);
    String fontFile = fontTable.getProperty(lookup);

    int fontStyle = Font.NORMAL;
    Color color = COLOR_BLACK;

    if ((style & LINK) != 0) {
        fontStyle += Font.UNDERLINE;
        color = COLOR_LINK;
    } else if ((style & UNDERLINE) != 0)
        fontStyle += Font.UNDERLINE;

    if ((style & STRIKETHROUGH) != 0)
        fontStyle += Font.STRIKETHRU;

    if (fontFile != null) {

        File file = new File(DefaultConfiguration.getWorkDir(), fontFile);
        if (file.exists() && file.isFile()) {

            try {
                String encoding = encTable.getProperty(lookup, BaseFont.CP1252);
                BaseFont bfComic = BaseFont.createFont(file.getAbsolutePath(), encoding, BaseFont.EMBEDDED);

                if ((style & AbstractConfiguration.ITALIC) > 0) {
                    if ((style & AbstractConfiguration.BOLD) > 0)
                        fontStyle += Font.BOLDITALIC;
                    else
                        fontStyle += Font.ITALIC;
                } else if ((style & AbstractConfiguration.BOLD) > 0)
                    fontStyle += Font.BOLD;

                if (fontStyle != Font.NORMAL)
                    font = new Font(bfComic, size, fontStyle, color);
                else
                    font = new Font(bfComic, size);

                if (font == null)
                    throw new IllegalArgumentException("Font null: " + fontFile);
            } catch (Exception e) {
                e.printStackTrace();
                throw new IllegalArgumentException("Font unusable");
            }
        } else
            DocletUtility.error("Font file not found: " + fontFile);
    } else {
        // Use predefined font
        String face = "";

        if (faceType == TEXT_FONT) {
            face = FontFactory.HELVETICA;

            if ((style & AbstractConfiguration.ITALIC) > 0) {
                if ((style & AbstractConfiguration.BOLD) > 0)
                    face = FontFactory.HELVETICA_BOLDOBLIQUE;
                else
                    face = FontFactory.HELVETICA_OBLIQUE;
            } else if ((style & AbstractConfiguration.BOLD) > 0)
                face = FontFactory.HELVETICA_BOLD;
        } else {
            face = FontFactory.COURIER;
            if ((style & ITALIC) > 0) {
                if ((style & BOLD) > 0)
                    face = FontFactory.COURIER_BOLDOBLIQUE;
                else
                    face = FontFactory.COURIER_OBLIQUE;
            } else if ((style & BOLD) > 0)
                face = FontFactory.COURIER_BOLD;
        }

        if (fontStyle != Font.NORMAL)
            font = FontFactory.getFont(face, size, fontStyle, color);
        else
            font = FontFactory.getFont(face, size);
    }

    return font;
}

From source file:org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManagerFactory.java

License:Open Source License

/**
 * Creates iText BaseFont with the given font family name.
 * //from w w w  .ja v  a2 s . com
 * @param ffn
 *            the specified font family name.
 * @return the created BaseFont.
 */
public BaseFont createFont(String familyName, int fontStyle) {
    String key = familyName + fontStyle;
    BaseFont bf = null;
    synchronized (baseFonts) {
        if (baseFonts.containsKey(key)) {
            bf = (BaseFont) baseFonts.get(key);
        } else {
            try {
                String fontEncoding = (String) fontEncodings.get(familyName);
                if (fontEncoding == null) {
                    fontEncoding = BaseFont.IDENTITY_H;
                }
                bf = FontFactory.getFont(familyName, fontEncoding, BaseFont.EMBEDDED, 14, fontStyle)
                        .getBaseFont();
            } catch (Throwable de) {
                logger.log(Level.WARNING, de.getMessage(), de);
            }
            baseFonts.put(key, bf);
        }
        if (bf == null && fontStyle != Font.NORMAL) {
            return createFont(familyName, Font.NORMAL);
        }
    }
    return bf;
}

From source file:org.eclipse.osee.framework.ui.skynet.util.TableWriterAdaptor.java

License:Open Source License

public void writeHeader(Table table, String[] headers) throws Exception {
    for (String header : headers) {
        Cell cell = new Cell();
        cell.setHeader(true);/*w w  w. jav a2  s . c  o m*/
        cell.setColspan(1);
        cell.setBackgroundColor(WebColors.getRGBColor("#d9d9d9"));
        cell.setHorizontalAlignment(ElementTags.ALIGN_CENTER);

        Font font = FontFactory.getFont("Times New Roman", BaseFont.CP1252, BaseFont.EMBEDDED, 9, Font.BOLD,
                WebColors.getRGBColor("#000000"));
        Paragraph paragraph = new Paragraph(header, font);
        paragraph.setAlignment(ElementTags.ALIGN_CENTER);
        cell.add(paragraph);
        table.addCell(cell);
    }
}

From source file:org.eclipse.osee.framework.ui.skynet.util.TableWriterAdaptor.java

License:Open Source License

public void writeRow(Table table, String... cellData) {
    for (String cellText : cellData) {
        Cell cell = new Cell();
        cell.setHeader(false);//from   ww w  .  jav a  2 s. co m
        cell.setColspan(1);
        Font font = FontFactory.getFont("Times New Roman", BaseFont.CP1252, BaseFont.EMBEDDED, 9, Font.NORMAL,
                WebColors.getRGBColor("#000000"));
        Paragraph paragraph = new Paragraph(cellText, font);
        cell.add(paragraph);
        table.addCell(cell);
    }
}

From source file:org.eclipse.osee.framework.ui.skynet.util.TableWriterAdaptor.java

License:Open Source License

public void writeDocument() throws DocumentException {
    Font font = FontFactory.getFont("Times New Roman", BaseFont.CP1252, BaseFont.EMBEDDED, 9, Font.BOLD,
            WebColors.getRGBColor("#000000"));
    Paragraph paragraph = new Paragraph(title, font);
    paragraph.setAlignment(ElementTags.ALIGN_CENTER);
    document.add(paragraph);/*from  w w  w .j  a  v a 2s.co  m*/
    if (table != null) {
        document.add(table);
    }
}

From source file:org.giavacms.common.filter.RendererFilter.java

License:Open Source License

public synchronized void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // Check to see if this filter should apply.
    @SuppressWarnings("unused")
    String renderType = request.getParameter("RenderOutputType");
    // if (renderType != null) {
    // Capture the content for this request
    ContentCaptureServletResponse capContent = new ContentCaptureServletResponse(response);
    filterChain.doFilter(request, capContent);

    try {//ww  w  . ja va 2s .  co m
        // Parse the XHTML content to a document that is readable by the
        // XHTML renderer.
        StringReader contentReader = new StringReader(capContent.getContent());
        InputSource source = new InputSource(contentReader);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new LocalHostEntityResolver());
        Document xhtmlContent = documentBuilder.parse(source);

        String title = "documento";
        NodeList titleNL = xhtmlContent.getElementsByTagName("title");
        if (titleNL != null && titleNL.getLength() > 0) {
            Node titleN = titleNL.item(0);
            if (titleN != null && titleN.getFirstChild() != null) {
                String titleS = StringUtils.clean(titleN.getFirstChild().getNodeValue());
                if (titleS != null && titleS.length() > 0) {
                    title = titleS;
                }
            }
        }

        ITextRenderer renderer = new ITextRenderer();

        try {
            String[] fonts = { "arialbd.ttf", "Times_New_Roman_Bold_Italic.ttf", "arialbi.ttf",
                    "Times_New_Roman_Bold.ttf", "ariali.ttf", "Times_New_Roman_Italic.ttf", "arial.ttf",
                    "Times_New_Roman.ttf", "Courier_New_Bold_Italic.ttf", "Verdana_Bold_Italic.ttf",
                    "Courier_New_Bold.ttf", "Verdana_Bold.ttf", "Courier_New_Italic.ttf", "Verdana_Italic.ttf",
                    "Courier_New.ttf", "Verdana.ttf" };

            for (String font : fonts) {
                renderer.getFontResolver().addFont("fonts/" + font, BaseFont.EMBEDDED);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        renderer.setDocument(xhtmlContent, null);
        renderer.layout();

        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=" + title + ".pdf");
        OutputStream browserStream = response.getOutputStream();
        renderer.createPDF(browserStream);
        return;

    } catch (SAXException e) {
        throw new ServletException(e);
    } catch (DocumentException e) {
        throw new ServletException(e);
    } catch (ParserConfigurationException e) {
        throw new ServletException(e);
    }

}