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

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

Introduction

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

Prototype

String WINANSI

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

Click Source Link

Document

A possible encoding.

Usage

From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

/**
 * Adds a text in the given pdf file.// w  w w . ja  v a  2  s.  co  m
 * @param pdfFileName
 * @param text
 * @param x
 * @param y
 * @param rotation
 * @param page
 * @throws Exception
 */
public void addText(String pdfFileName, String text, int x, int y, int rotation, int page) throws Exception {
    // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java
    // 1. copy
    File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf");
    copyFile(new File(pdfFileName), tmpPDFFile);
    // 2. add text
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
    // we create a stamper that will copy the document to a new file
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName));
    // adding content to each page
    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
    over = stamp.getOverContent(page);
    over.beginText();
    over.setFontAndSize(bf, 32);
    over.setTextMatrix(30, 30);
    over.setColorFill(java.awt.Color.RED);
    over.showTextAligned(Element.ALIGN_LEFT, text, x, y, rotation);
    over.endText();
    // closing PdfStamper will generate the new PDF file
    stamp.close();
}

From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java

License:Open Source License

@Override
public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) {
    logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION,
            new String[] { String.valueOf(idRelevePrestation) }));
    final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto();
    critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation);
    if (idPersonne != null) {
        critereSelectionRelevePrestationDto.setIdPersonne(idPersonne);
    }/* w  ww .  j  a  va 2  s .  co  m*/
    final List<RelevePrestation> lstReleves = relevePrestationDao
            .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null);
    if (lstReleves.size() == 1) {
        final RelevePrestation releve = lstReleves.get(0);
        final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER);
        FichierDto fichier;
        final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier();
        try {
            fichier = new FichierDto();
            fichier.setNomFichier(releve.getNomFichierCommercial());
            if (duplicata) {
                // On appose la mention "DUPLICATA" sur toutes les pages du relev.
                try {
                    final PdfReader reader = new PdfReader(cheminFichier);
                    final int nombrePages = reader.getNumberOfPages();
                    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI,
                            BaseFont.EMBEDDED);
                    final PdfStamper stamp = new PdfStamper(reader,
                            new FileOutputStream(FICHIER_DUPLICATA_TEMP));
                    final int taillePolice = 56;
                    final int positionX = ((int) PageSize.A4.getWidth()) / 2;
                    final int positionY = ((int) PageSize.A4.getHeight()) / 2;
                    final int rotation = 30;
                    for (int i = 1; i <= nombrePages; i++) {
                        final PdfContentByte over = stamp.getOverContent(i);
                        over.beginText();
                        over.setColorFill(Color.GRAY);
                        final PdfGState gs1 = new PdfGState();
                        gs1.setFillOpacity(NIVEAU_TRANSPARENCE);
                        over.setGState(gs1);
                        over.setFontAndSize(bf, taillePolice);
                        over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY,
                                rotation);
                        over.endText();
                    }
                    stamp.close();
                    reader.close();
                    fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP)));
                    final File file = new File(FICHIER_DUPLICATA_TEMP);
                    file.delete();
                } catch (DocumentException e) {
                    throw new TechnicalException(
                            messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA,
                                    new String[] { releve.getNomFichier() }));
                }
            } else {
                fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier)));
            }
            fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType());
        } catch (FileNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (IOException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicParseException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicMatchNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        }
        return fichier;
    } else {
        throw new TechnicalException(
                messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE));
    }
}

From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java

License:GNU General Public License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)/*from w  ww.j  av  a2 s. c o  m*/
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {
        headerImage = Image.getInstance(getLogoUrl());
        table = new PdfPTable(new float[] { 1f, 2f });
        Phrase p = new Phrase();
        Chunk ck = new Chunk(cr.getTitle(), new Font(Font.HELVETICA, 16, Font.BOLD));
        p.add(ck);
        p.add(Chunk.NEWLINE);
        ck = new Chunk(ConversationExporter.formatName(account), new Font(Font.HELVETICA, 12, Font.BOLDITALIC));
        p.add(ck);
        p.add(Chunk.NEWLINE);
        ck = new Chunk(cm.length + " messages", new Font(Font.HELVETICA, 10));
        p.add(ck);
        table.getDefaultCell().setBorder(0);
        table.addCell(new Phrase(new Chunk(headerImage, 0, 0)));
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(p);
        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);
        tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100));
        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:gov.anl.aps.cdb.portal.plugins.support.icmsLink.IcmsWatermarkUtility.java

License:Open Source License

/**
 * Adds a stamp of some metadata to ICMS documents.
 *
 * Function Credit: Thomas Fors/*from  w ww.  j ava 2s  .c o m*/
 *     
 * @return byte array ologgerf the stamped PDF file
 * @throws DocumentException - Error loading pdfstamper or creating font
 * @throws IOException - Error performing IO operation 
 * @throws Base64DecodingException - Error converting downloadContent string to byte[]
 */
private byte[] addWatermarkToPDFFile() throws Base64DecodingException, DocumentException, IOException {
    byte[] pdfBytes = Base64.decode(downloadContentBase64Encoded);

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm:ss a");
    LocalDateTime now = LocalDateTime.now();
    String downloadTime = dtf.format(now);

    UserInfo user = (UserInfo) SessionUtility.getUser();
    String username = null;
    if (user != null) {
        username = user.getUsername();
    } else {
        username = "unknown user";
    }
    String bottomMessage = "Downloaded via APS CDB by: " + username + " at " + downloadTime;

    controlledRev = updateOptionalValue(controlledRev);
    dnsCollectionId = updateOptionalValue(dnsCollectionId);
    dnsDocNumber = updateOptionalValue(dnsDocNumber);

    String watermarkContents = "Content ID: " + docName;
    watermarkContents += "      Rev: " + controlledRev;
    watermarkContents += "      Released: " + date;
    watermarkContents += "      DNS Collection ID: " + dnsCollectionId;
    watermarkContents += "      DNS Document ID: " + dnsDocNumber;

    PdfReader pdfReader = new PdfReader(pdfBytes);
    int n = pdfReader.getNumberOfPages();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfStamper stamp = new PdfStamper(pdfReader, out);

    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    for (int i = 0; i < n; i++) {
        over = stamp.getOverContent(i + 1);
        over.beginText();
        over.setTextMatrix(30, 30);
        over.setFontAndSize(bf, 10);
        over.setColorFill(new Color(0x80, 0x80, 0x80));
        over.showTextAligned(Element.ALIGN_LEFT, watermarkContents, 25, 25, 90);
        over.showTextAligned(Element.ALIGN_LEFT, bottomMessage, 50, 10, 0);
        if (status.equals(ICMS_UNDER_REV_STATUS)) {
            over.setColorFill(new Color(0xFF, 0x00, 0x00));
        }
        //over.showTextAligned(Element.ALIGN_LEFT, status, 25, 25 + bf.getWidthPoint(watermarkContents + " - ", 10), 90);

        over.endText();
    }
    stamp.close();

    return out.toByteArray();
}

From source file:jgnash.ui.report.FontRegistry.java

License:Open Source License

private void registerFont(final String path) {
    try {/*from  w w  w.j av a2  s. c  om*/
        if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf")
                || path.toLowerCase().indexOf(".ttc,") > 0) {
            Object allNames[] = BaseFont.getAllFontNames(path, BaseFont.WINANSI, null);

            String[][] names = (String[][]) allNames[2]; //full name
            for (String[] name : names) {
                registeredFontMap.put(name[3].toLowerCase(), path);
            }

        } else if (path.toLowerCase().endsWith(".ttc")) {
            String[] names = BaseFont.enumerateTTCNames(path);
            for (int i = 0; i < names.length; i++) {
                registerFont(path + "," + i);
            }
        } else if (path.toLowerCase().endsWith(".afm") || path.toLowerCase().endsWith(".pfm")) {
            BaseFont bf = BaseFont.createFont(path, BaseFont.CP1252, false);
            String fullName = bf.getFullFontName()[0][3].toLowerCase();
            registeredFontMap.put(fullName, path);
        }
    } catch (DocumentException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.algem.contact.TeacherCtrl.java

License:Open Source License

private File getFollowUpAsPDF(String userId, String from, String to)
        throws IOException, BadElementException, DocumentException {
    String path = "/tmp/" + "suivi-" + userId + ".pdf";
    File f = new File(path);
    LOGGER.log(Level.INFO, f.getName());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open()
    document.open();/*from  w ww  .  jav  a  2  s.  c o  m*/

    PdfPTable table = new PdfPTable(10);
    table.setWidthPercentage(100);
    table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f });

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
    BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false);
    Font normalFont = new Font(bf, 10);
    Font boldFont = new Font(bfb, 10);

    String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE);
    String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE);
    String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " "
            + organization.get("name.label");
    String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to;
    PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont));

    headerCell.setBackgroundColor(Color.LIGHT_GRAY);
    headerCell.setColspan(10);
    table.addCell(headerCell);

    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("student.label", null, CTX_LOCALE), boldFont)));
    String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE);
    table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont)));

    List<ScheduleElement> items = getFollowUpSchedules(userId, from, to);
    //LOGGER.log(Level.INFO, items.toString());
    for (ScheduleElement e : items) {
        List<ScheduleRangeElement> ranges = new ArrayList<ScheduleRangeElement>(
                (Collection<? extends ScheduleRangeElement>) e.getRanges());

        for (ScheduleRangeElement r : ranges) {
            String status = CommonDao.getAbsenceFromNumberStatus(r.getFollowUp().getStatus());
            String note = r.getFollowUp().getNote();
            String content1 = r.getFollowUp().getContent();
            String content2 = e.getFollowUp().getContent();
            table.addCell(new Phrase(e.getDateFr().toString(), normalFont));
            table.addCell(new Phrase(r.getStart() + "-" + r.getEnd(), normalFont));
            table.addCell(new Phrase(new Hour(r.getLength()).toString(), normalFont));
            table.addCell(new Phrase(e.getDetail().get("room").getName(), normalFont));
            table.addCell(new Phrase(e.getDetail().get("course").getName(), normalFont));
            table.addCell(new Phrase(r.getPerson().getFirstName() + " " + r.getPerson().getName(), normalFont));
            table.addCell(new Phrase(status, normalFont));
            table.addCell(new Phrase(note == null ? "" : note, normalFont));
            table.addCell(new Phrase(content1 == null ? "" : content1.replaceAll("[\r\n]", " "), normalFont));
            table.addCell(new Phrase(content2 == null ? "" : content2.replaceAll("[\r\n]", " "), normalFont));
        }
    }

    document.add(table);
    document.close();
    byte[] pdfBytes = byteArrayOutputStream.toByteArray();
    Files.write(Paths.get(path), pdfBytes);
    return f;
}

From source file:net.algem.security.UserCtrl.java

License:Open Source License

private File getFollowUpAsPDF(String userId, String from, String to)
        throws IOException, BadElementException, DocumentException {
    String path = "/tmp/" + "suivi-" + userId + ".pdf";
    File f = new File(path);
    LOGGER.log(Level.INFO, f.getName());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open()
    document.open();// w w w . ja v  a  2 s . com

    PdfPTable table = new PdfPTable(10);
    table.setWidthPercentage(100);
    table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f });

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
    BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false);
    Font normalFont = new Font(bf, 10);
    Font boldFont = new Font(bfb, 10);

    String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE);
    String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE);
    String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " "
            + organization.get("name.label");
    String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to;
    PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont));

    headerCell.setBackgroundColor(Color.LIGHT_GRAY);
    headerCell.setColspan(10);
    table.addCell(headerCell);

    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("teacher.label", null, CTX_LOCALE), boldFont)));
    String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE);
    table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont)));

    fillPdfTable(table, getFollowUpSchedules(userId, from, to), normalFont);

    document.add(table);
    document.close();
    byte[] pdfBytes = byteArrayOutputStream.toByteArray();
    Files.write(Paths.get(path), pdfBytes);
    return f;
}

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

License:Mozilla Public License

/**
 * Returns BaseFont for text of visible signature;
 * //  w w  w . j ava2s  . com
 * @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.
 * /*  ww w . j  a v a  2  s  .c  om*/
 * @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.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) {
    File tempFile = null;//from   ww  w  . j a v  a 2  s  .c om

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampText.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                String chosenText = stampText.getText();

                if (!chosenText.equals("")) {

                    String chosenFont = stampText.getFontName();
                    Color chosenFontColor = stampText.getFontColor();
                    int chosenFontSize = stampText.getFontSize();

                    int chosenRotation = stampText.getRotation();
                    String chosenPlacement = stampText.getPlacement();

                    String chosenHorizontalPosition = stampText.getHorizontalPosition();
                    String chosenVerticalPosition = stampText.getVerticalPosition();

                    float chosenHorizontalOffset = stampText.getHorizontalOffset();
                    float chosenVerticalOffset = stampText.getVerticalOffset();

                    BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false);

                    PdfContentByte cb;
                    if (chosenPlacement.equals("Overlay"))
                        cb = stamp.getOverContent(page);
                    else
                        cb = stamp.getUnderContent(page);

                    cb.beginText();
                    cb.setColorFill(chosenFontColor);
                    cb.setFontAndSize(font, chosenFontSize);

                    int currentRotation = currentPageData.getRotation(page);
                    Rectangle pageSize;
                    if (currentRotation == 90 || currentRotation == 270)
                        pageSize = reader.getPageSize(page).rotate();
                    else
                        pageSize = reader.getPageSize(page);

                    float startx;
                    float starty;

                    if (chosenVerticalPosition.equals("From the top")) {
                        starty = pageSize.height();
                    } else if (chosenVerticalPosition.equals("Centered")) {
                        starty = pageSize.height() / 2;
                    } else {
                        starty = 0;
                    }

                    if (chosenHorizontalPosition.equals("From the left")) {
                        startx = 0;
                    } else if (chosenHorizontalPosition.equals("Centered")) {
                        startx = pageSize.width() / 2;
                    } else {
                        startx = pageSize.width();
                    }

                    cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset,
                            starty + chosenVerticalOffset, chosenRotation);
                    cb.endText();
                }
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}