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

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

Introduction

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

Prototype

public static BaseFont createFont(String name, String encoding, boolean embedded)
        throws DocumentException, IOException 

Source Link

Document

Creates a new font.

Usage

From source file:questions.tables.AddTableAsHeaderFooter.java

public void onOpenDocument(PdfWriter writer, Document document) {
    try {//w ww .ja  va  2s  . c om
        // initializations
        tpl = writer.getDirectContent().createTemplate(150, 18);
        Rectangle rect = new Rectangle(0, 0, 150, 18);
        rect.setBackgroundColor(Color.GRAY);
        tpl.setBoundingBox(rect);
        tpl.rectangle(rect);
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
        // header
        headerTable = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Paragraph("Header Text"));
        headerTable.addCell(cell);
        headerTable.setTotalWidth(document.right() - document.left());
        headerTable.setLockedWidth(true);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape/*  w w  w  .j  a v  a2 s.  com*/
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

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

From source file:s2s.report.MyPageEvents.java

License:GNU General Public License

@Override
public void onOpenDocument(PdfWriter writer, Document m_document) {
    try {/*from   w  w w .  ja  va 2s  . c  o  m*/
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb = writer.getDirectContent();
        template = cb.createTemplate(50, 50);
        m_rect = bRotate ? PageSize.A4.rotate() : PageSize.A4;
    } catch (DocumentException de) {
        de.printStackTrace(System.err);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    }
}

From source file:test.poi.ConvertDocxResumeToPDF.java

License:LGPL

private static void create() {
    long startTime = System.currentTimeMillis();

    try {/*w  ww .j a  v  a 2  s  .c  o  m*/
        // 1) Load docx with POI XWPFDocument
        XWPFDocument document = new XWPFDocument(
                ConvertDocxResumeToPDF.class.getClassLoader().getResourceAsStream("DocxResume.docx"));

        // 2) Convert POI XWPFDocument 2 PDF with iText
        File outFile = new File("d:/DocxResume.pdf");
        outFile.getParentFile().mkdirs();

        OutputStream out = new FileOutputStream(outFile);
        PdfOptions options = PdfOptions.create();
        //
        options.fontProvider(new IFontProvider() {

            @Override
            public Font getFont(String familyName, String encoding, float size, int style, Color color) {
                try {
                    BaseFont bfChinese = BaseFont.createFont("c:/Windows/Fonts/arialuni.ttf",
                            BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    Font fontChinese = new Font(bfChinese, size, style, color);
                    if (familyName != null)
                        fontChinese.setFamily(familyName);
                    return fontChinese;
                } catch (Throwable e) {
                    e.printStackTrace();
                    return ITextFontRegistry.getRegistry().getFont(familyName, encoding, size, style, color);
                }
            }
        });

        PdfConverter.getInstance().convert(document, out, options);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    System.out.println("Generate DocxResume.pdf with " + (System.currentTimeMillis() - startTime) + " ms.");
}

From source file:textdisplay.TagFilter.java

License:Educational Community License

public void replaceTagsWithPDFEncoding(String[] tags, styles[] tagStyles, OutputStream os)
        throws DocumentException {
    //   FileWriter w = null;

    try {//from   w  w w. ja v  a  2s  . c o  m
        BaseFont bf = BaseFont.createFont("/usr/Junicode.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        Document doc = new Document();
        PdfWriter p = PdfWriter.getInstance(doc, os);
        doc.open();
        Paragraph para = new Paragraph();
        para.setFont(new Font(bf, 12, Font.NORMAL));
        //doc.add(para);
        Font italic = new Font(bf, 12, Font.ITALIC);
        Font bold = new Font(bf, 12, Font.BOLD);
        Font underlined = new Font(bf, 12, Font.UNDERLINE);

        StringBuilder chunkBuffer = new StringBuilder(""); //holds the next bit of content that will be added to the pdf as a chunk
        styles chunkStyle = null; //the style to be applied to chunkBuffer when it gets added to the document
        String chunkTag = "";
        Stack<String> wrappingTags = new Stack();
        Stack<styles> wrappingStyles = new Stack();
        String content = text;
        Boolean inTag = false; //is this inside a tag, meaning between the < and >
        String tagTextBuffer = ""; //the text of the tag, including name and any parameters
        Boolean beingTagged = false; //Is the parser currently reading character data that is surrounded by a tag that demands styling
        for (int charCounter = 0; charCounter < this.text.length(); charCounter++) {

            if (text.charAt(charCounter) == '>') {
                inTag = false;
                //if this was a self closing tag, dont do anything
                if (tagTextBuffer.contains("/>")) {
                    tagTextBuffer = "";
                } else {
                    //this is a closing tag, save the chunk and pop the tag and style off of the stack
                    if (tagTextBuffer.startsWith("/")) {
                        if (chunkStyle != null)
                            System.out.print(" closing tag " + tagTextBuffer + " with style "
                                    + chunkStyle.name() + "\n");
                        else
                            System.out.print(" closing tag " + tagTextBuffer + " with style null" + "\n");
                        if (chunkStyle == styles.paragraph)
                            chunkBuffer = new StringBuilder("\n" + chunkBuffer);
                        Chunk c = new Chunk(chunkBuffer.toString());
                        styleChunk(c, chunkStyle);

                        if (chunkStyle != styles.remove)
                            para.add(c);
                        chunkBuffer = new StringBuilder("");
                        chunkStyle = null;
                        chunkTag = "";
                        if (!wrappingStyles.empty()) {
                            chunkStyle = wrappingStyles.pop();
                            chunkTag = wrappingTags.pop();
                        }
                        tagTextBuffer = "";

                    } else {
                        //this is the closing bracket of an opening tag
                        String tagName = tagTextBuffer.split(" ")[0];
                        System.out.print("tag is " + tagName + "\n");
                        for (int i = 0; i < tags.length; i++) {

                            if (tags[i].compareTo(tagName) == 0) {
                                // this is a tag that is suposed to be styled in the pdf
                                if (chunkStyle != null) {
                                    //this tag is nested in a tag that was already applying styling. Add this chunk to the pdf and put the tag/style
                                    //for the previous tag on the stack, so when this new tag ends, the previous styling will resume.
                                    if (chunkStyle == styles.paragraph)
                                        chunkBuffer = new StringBuilder("\n" + chunkBuffer);
                                    Chunk c = new Chunk(chunkBuffer.toString());
                                    styleChunk(c, chunkStyle);
                                    if (chunkStyle != styles.remove)
                                        para.add(c);
                                    wrappingStyles.add(chunkStyle);
                                    wrappingTags.add(chunkTag);
                                    chunkTag = tagName;
                                    chunkStyle = tagStyles[i];
                                    chunkBuffer = new StringBuilder("");
                                } else {
                                    Chunk c = new Chunk(chunkBuffer.toString());
                                    para.add(c);
                                    chunkTag = tagName;
                                    chunkStyle = tagStyles[i];
                                    chunkBuffer = new StringBuilder("");
                                }
                            }
                        }
                        tagTextBuffer = "";
                    }
                }
            }
            if (inTag) {
                tagTextBuffer += text.charAt(charCounter);
            }
            if (text.charAt(charCounter) == '<') {
                if (inTag) {
                    //if we hit another < before hitting a > this was not a tag, so add the tagTextBuffer to the chunk. It was simply conent.
                    chunkBuffer.append(tagTextBuffer);
                    tagTextBuffer = "";
                }
                inTag = true;
            }
            if (!inTag && text.charAt(charCounter) != '>') {
                chunkBuffer.append(text.charAt(charCounter));
            }
        }
        Chunk c = new Chunk(chunkBuffer.toString());
        para.add(c);
        doc.newPage();
        doc.add(para);
        doc.newPage();
        doc.close();
    } catch (IOException ex) {
        Logger.getLogger(TagFilter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }

}

From source file:textdisplay.TagFilter.java

License:Educational Community License

/**Apply a style (font) to a chunk of pdf text*/
private void styleChunk(Chunk c, styles s) {
    try {/*from w  ww .j a v a 2 s.c  o m*/

        BaseFont bf = BaseFont.createFont("/usr/Junicode.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        BaseFont ita = BaseFont.createFont("/usr/Junicode-Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        BaseFont bol = BaseFont.createFont("/usr/Junicode-Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        if (bf.charExists(540)) {
            System.out.print("font cant do 540\n");
        }
        Font italic = new Font(ita, 12, Font.ITALIC);
        Font bold = new Font(bol, 12, Font.BOLD);
        Font underlined = new Font(bf, 12, Font.UNDERLINE);
        Font superscript = new Font(bf, 9, Font.NORMAL);

        if (s == styles.bold) {
            c.setFont(bold);
        }
        if (s == styles.italic) {
            c.setFont(italic);
        }
        if (s == styles.underlined) {
            c.setFont(underlined);
        }
        if (s == styles.superscript) {
            c.setTextRise(7.0f);
            c.setFont(superscript);

        }

        //wipe out that content

    } catch (DocumentException ex) {
        Logger.getLogger(TagFilter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TagFilter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

private static void drawSequenceNumber(PdfWriter writer, float x, float y, int seq) {
    PdfContentByte cb = writer.getDirectContent();
    try {//from ww w  . jav a  2s .c om
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 16);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, new Integer(seq).toString() + ".", x, y, 0f);
    cb.endText();
    cb.stroke();

    //return tp2;
}

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteerBadgePdfView.java

License:Open Source License

/**
 * Adds the Volunteer's name to the Badge.
 *
 * @param content to be added/* w ww.j  a v a  2s . co  m*/
 * @param name concatenated String of forename and surname
 */
private static void addVolunteerName(PdfContentByte content, String name)
        throws DocumentException, IOException {
    content.beginText();
    content.moveText(183, 470);

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1257, false);
    content.setFontAndSize(bf, 16);
    content.setColorFill(Color.BLACK);
    content.showText(name);
    content.endText();
}

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteerBadgePdfView.java

License:Open Source License

/**
 * Adds a Barcode39 of the id number of a Volunteer to the Badge.
 *
 * @param content to be added/*from  www  . jav  a2s. com*/
 * @param id volunteer id
 * @throws DocumentException
 * @throws IOException
 */
private static void addBarcode(PdfContentByte contentByte, Integer id) throws IOException, DocumentException {
    Barcode39 barcode = new Barcode39();
    BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
    barcode.setFont(baseFont);
    barcode.setSize(6);
    barcode.setCode(id.toString());
    contentByte.setColorFill(Color.BLACK);
    Image baecodeImg = barcode.createImageWithBarcode(contentByte, null, null);
    contentByte.addImage(baecodeImg, 75, 0, 0, 35, 338, 344);
}

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteerBadgePdfView.java

License:Open Source License

/**
 * Adds a department to the Badge. The badge only shows the first
 * departmental assignment of a Volunteer, not all their departmental
 * assignments./*from   www .j  av  a  2  s  .c  o m*/
 *
 * @param content to be added
 * @param department of the volunteer
 */
private static void addDepartment(PdfContentByte content, String department)
        throws DocumentException, IOException {
    content.beginText();
    content.moveText(183, 453);

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1257, false);
    content.setFontAndSize(bf, 14);
    content.showText(department);
    content.endText();
}