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

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

Introduction

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

Prototype

String COURIER

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

Click Source Link

Document

This is a possible value of a base 14 type 1 font

Usage

From source file:ExamplePdfPrinter.java

License:Open Source License

public static void main(String[] args) throws Exception {
    SpooledFile spooledFile = null; // TODO: provide your spool file!
    final IScsDataProvider dp = As400ScsDataProviderFactory.getPrintObjectDataProvider(spooledFile);
    final ReaderConfig rcfg = ReaderConfig.getDefault();
    final SCSStreamReader reader = new SCSStreamReader(dp, rcfg);

    PrinterConfig pcfg = PrinterConfig.getDefault();
    float FONT_SIZE = 9.0F;
    float leading = FONT_SIZE * 1.05F;

    // calculate font, font size, and margins for the PDF
    final Font monoSpacedFont = FontFactory.getFont(BaseFont.COURIER, FONT_SIZE);
    final Font monoSpacedFontBold = FontFactory.getFont(BaseFont.COURIER_BOLD, Font.BOLD);
    Rectangle pageSize = new Rectangle(PageSize.A4);
    final Document pdfdoc = new Document(pageSize);

    final FileOutputStream fos = new FileOutputStream("test.pdf");
    final PdfWriter pdfwriter = PdfWriter.getInstance(pdfdoc, fos);
    pdfdoc.open();/*w  w w .j a  v  a2  s . c om*/

    PdfPrinter pdfprinter = new PdfPrinter(pcfg, pdfdoc, monoSpacedFont, monoSpacedFontBold, leading);

    try {
        while (reader.hasNext()) {
            final IPrinterMicroCommand event = reader.next();
            if (event == null)
                break;
            pdfprinter.runMicroCommand(event);
        }
    } catch (EndOfFileSignal e) {
        System.out.println("eof.");
    }

    pdfprinter.finish();
    pdfdoc.close();
    pdfwriter.close();
}

From source file:br.org.archimedes.io.pdf.elements.TextExporter.java

License:Open Source License

public void exportElement(Text text, Object outputObject) throws IOException {

    PDFWriterHelper helper = (PDFWriterHelper) outputObject;
    PdfContentByte cb = helper.getPdfContentByte();

    Point lowerLeft = text.getLowerLeft();
    Point docPoint = helper.modelToDocument(lowerLeft);

    BaseFont font = null;//from  w  w  w  . j  a  va  2 s. co  m
    try {
        font = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
        // Problems creating the font. This means the current
        // platform does not support this encoding or font.
        System.err.println(Messages.TextExporter_FontCreatingError);
        e.printStackTrace();
    }
    cb.setFontAndSize(font, (float) text.getSize());
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    cb.beginText();
    cb.moveText((float) docPoint.getX(), (float) docPoint.getY());
    double angle = 0;
    try {
        angle = Geometrics.calculateAngle(new Point(0, 0), text.getDirection().getPoint());
    } catch (NullArgumentException e) {
        // Shouldn't happen since the text MUST have a direction to exists
        // and the point 0,0 is valid
        e.printStackTrace();
    }
    float degreeAngle = (float) (angle * 180 / Math.PI);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text.getText(), (float) docPoint.getX(),
            (float) docPoint.getY(), degreeAngle);
    cb.endText();
}

From source file:ch.gpb.elexis.cst.view.CstResultPart.java

License:Open Source License

private void makeActions(final Control viewer) {

    actionScreenshot = new Action() {
        public void run() {
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }/*from   www  .  ja va 2s. c o  m*/

            GC gc = null;
            Image image = null;
            try {

                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.png", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }

                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) {
                if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) {

                    if (profile.getAusgabeRichtung()) {
                        image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height);

                    } else {
                        image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                    }
                } else {
                    image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                }

                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);

                gc.dispose();

                loader.data = new ImageData[] { image.getImageData() };
                loader.save(selected, SWT.IMAGE_PNG);

            } catch (Exception e) {
                log.error("Error saving png: " + e.toString());
                showMessage("Error while saving PNG", e.getMessage());
            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
            }

        }
    };
    actionScreenshot.setText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT));
    actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH));

    // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten
    actionPdf = new Action() {
        public void run() {

            //////////////////////////
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }

            GC gc = null;
            Image image = null;
            try {
                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.pdf", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }
                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                int printHeigth = 1123;
                int printWidth = 794;
                if (profile.getAusgabeRichtung()) {
                    printHeigth = 794;
                    printWidth = 1123;

                }

                // get the image from the viewport
                image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height);
                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);
                gc.dispose();

                // prepare title data
                //Date date = new Date();
                //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy  HH:mm");

                Patient patient = Patient.load(profile.getKontaktId());
                //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi ";
                String sTitle;
                sTitle = profile.getOutputHeader() == null ? "No header configured!"
                        : profile.getOutputHeader();

                if (sTitle == null || sTitle.length() == 0) {
                    sTitle = "No header configured!";
                }
                sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime();

                // get option (paging to A4/ in one piece)
                int pdfOutputOption = 0;
                boolean onePage = true;

                PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell());
                dialog.create();

                if (dialog.open() == Window.OK) {
                    pdfOutputOption = dialog.getPdfOutputOption();
                    if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) {
                        onePage = true;
                    } else {

                        onePage = false;
                    }
                }

                float docHeight = viewer.getBounds().height;
                docHeight = docHeight / 7.5f;

                float fontSize = 12f;

                if (docHeight < 360f) {
                    docHeight = 360f;
                }

                BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData());

                // create an Itextt Image from AWT BufferedImage
                com.lowagie.text.Image itextImage = null;
                java.awt.Image awtImage = null;

                try {
                    awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource());
                    itextImage = com.lowagie.text.Image.getInstance(awtImage, null);

                } catch (Exception e) {
                    log.error("Error on image loading: " + e.toString());
                    e.printStackTrace();
                }

                // only for debugging

                //loader.data = new ImageData[] { image.getImageData() };
                //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG);

                Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f);

                // is it a4 quer?
                if (profile.getAusgabeRichtung()) {
                    pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f);

                }

                //System.out.println("pagesize: " + pagesize.toString());

                Document document;
                if (onePage) {
                    document = new Document(pagesize);

                } else {
                    document = new Document(PageSize.A4);
                    if (profile.getAusgabeRichtung()) {
                        document = new Document(PageSize.A4.rotate());
                    }

                }

                document.addCreationDate();

                try {
                    // creation of the different writers
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected));

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

                    com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize);

                    com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize);

                    fontTimes.setSize(fontSize);
                    fontTimes.setStyle(com.lowagie.text.Font.ITALIC);

                    Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize,
                            com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0)));

                    com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader);

                    // headers and footers must be added before the document
                    // is opened

                    Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA,
                            fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0)));

                    Phrase phraseFooter = new Phrase(chunkFooter);
                    phraseFooter.setFont(fontHelv12);

                    HeaderFooter footer = new HeaderFooter(phraseFooter, true);
                    footer.setBorder(Rectangle.NO_BORDER);
                    footer.setAlignment(Element.ALIGN_CENTER);

                    document.setFooter(footer);

                    Phrase headerPhrase = new Phrase(sTitle);
                    headerPhrase.setFont(fontTimes);

                    HeaderFooter header = new HeaderFooter(phraseHeader, false);
                    header.setBorder(Rectangle.BOTTOM);
                    header.setBorderWidth(0.5f);
                    header.setAlignment(Element.ALIGN_LEFT);
                    document.setHeader(header);

                    document.open();

                    //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight());

                    if (onePage) {

                        int scale = 66;
                        itextImage.scalePercent(scale);

                        document.add(itextImage);

                    } else {

                        BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth);

                        for (int i = 0; i < imageChunks.length; i++) {

                            com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance(
                                    Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null);

                            // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer
                            float imgWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float imgHeigth = itextImage.getHeight() * 0.75f;

                            itextImage2.setAbsolutePosition(30, 20);
                            int scale = 66;
                            itextImage2.scalePercent(scale);

                            document.add(itextImage2);
                            document.newPage();

                        }

                    }

                    // we're done!
                    document.close();

                    ///////////////////////////////

                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    showMessage("Error while generating PDF", ex.getMessage());
                }

            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
                /*
                image.dispose();
                gc.dispose();
                */
            }

        }
    };

    actionPdf.setText(Messages.Cst_Text_Save_as_pdf);
    actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf);
    /*
     * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages()
     * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
     */
    actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH));

}

From source file:com.kahlon.guard.controller.DocumentManager.java

/**
 *
 * @param document/*  ww  w .  j a va 2s. co m*/
 */
public void preProcessPDF(Object document) {
    try {

        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);

        Document pdf = (Document) document;
        pdf.setPageSize(PageSize.A4);
        pdf.setMargins(5f, 5f, 10f, 5f);

        // headers and footers must be added before the document is opened
        HeaderFooter footer = new HeaderFooter(new Phrase("page: ", new Font(bf_courier)), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);
        pdf.setFooter(footer);

        //            HeaderFooter header = new HeaderFooter(
        //                        new Phrase("This is a header without a page number", new Font(bf_courier)), false);
        //            header.setAlignment(Element.ALIGN_CENTER);
        //            pdf.setHeader(header);

        pdf.open();

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);

        pdf.add(Image.getInstance(logo));

        Person person = context.getSelectedPerson().getDisplayPerson();

        String name = FacesMessageUtil.getMessage("person.name") + " : " + person.getName();
        String age = FacesMessageUtil.getMessage("person.age") + " : " + Integer.toString(person.getAge());
        String gender = FacesMessageUtil.getMessage("person.gender") + " : "
                + person.getGender().getDescription();
        String race = FacesMessageUtil.getMessage("person.ethnicity") + " : "
                + person.getEthnicity().getDescription();

        Person rootPerson = person.getRootPerson();
        PersonImage imgp = imageService.getLastestPersonImage(rootPerson.getId());
        Image imgb = Image.getInstance(imgp.getContent());
        imgb.scaleToFit(100, 120);

        PdfPTable headerTable = new PdfPTable(2);

        PdfPTable personTable = new PdfPTable(1);
        personTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase(name));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(age));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(gender));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(race));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        BarcodePDF417 pdf417 = new BarcodePDF417();
        pdf417.setText(Integer.toString(person.getId()));
        Image img = pdf417.getImage();
        img.scalePercent(150, 60 * pdf417.getYHeight());
        cell = new PdfPCell(img);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(15);
        personTable.addCell(cell);

        cell.addElement(personTable);
        headerTable.addCell(cell);

        cell = new PdfPCell(imgb);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        headerTable.addCell(cell);

        headerTable.setSpacingAfter(15);
        pdf.add(headerTable);

        LineSeparator lineSeparator = new LineSeparator();
        lineSeparator.setPercentage(82);
        pdf.add(lineSeparator);
        Paragraph space = new Paragraph();
        space.add("");
        space.setSpacingAfter(15);
        pdf.add(space);

    } catch (IOException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (BadElementException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (DocumentException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (Exception e) {
        logger.log(Level.INFO, e.getMessage());
    }

}

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();/*from w  ww. j a  va2 s. c o  m*/

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

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

License:Open Source License

/**
* write a label in pdf document.//w  ww .ja v  a  2s .  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:org.apache.maven.doxia.module.itext.ITextFont.java

License:Apache License

/**
 * Convenience method to get a defined MonoSpaced font depending the wanted style and size.
 *
 * @param style the font style.//w  w  w .j  ava2s .  com
 * @param size the font size.
 * @param color the font color.
 * @return a font the font.
 */
public static Font getMonoSpacedFont(int style, float size, Color color) {
    try {
        return new Font(BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, false), size, style, color);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.apache.poi.xwpf.converter.internal.itext.XWPFFontRegistry.java

License:Open Source License

@Override
protected String resolveFamilyName(String familyName, int style) {
    boolean bold = isBold(style);
    boolean italic = isItalic(style);

    if (COURRIER_NEW_FONT_FAMILY_NAME.equals(familyName)) {
        if (bold && italic) {
            return BaseFont.COURIER_BOLDOBLIQUE;
        } else if (bold) {
            return BaseFont.COURIER_BOLD;
        } else if (italic) {
            return BaseFont.COURIER_OBLIQUE;
        }/*from  w  w w  .  j a  v  a 2  s .c  o m*/
        return BaseFont.COURIER;
    }

    if (TIMES_NEW_ROMAN_FONT_FAMILY_NAME.equals(familyName)) {
        if (bold && italic) {
            return BaseFont.TIMES_BOLDITALIC;
        } else if (bold) {
            return BaseFont.TIMES_BOLD;
        } else if (italic) {
            return BaseFont.TIMES_ITALIC;
        }
        return BaseFont.TIMES_ROMAN;
    }

    return familyName;
}

From source file:org.oscarehr.phr.web.PHRUserManagementAction.java

License:Open Source License

public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username,
        String password) throws Exception {
    log.debug("Demographic " + demographicNo + " username " + username + " password " + password);
    DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao");
    Demographic demographic = demographicDao.getDemographic(demographicNo);

    final String PAGESIZE = "printPageSize";
    Document document = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;//w  w  w  .j a  va2  s  .co  m

    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = "TITLE";
        String template = "MyOscarLetterHead.pdf";

        Properties printCfg = getCfgProp();

        String[] cfgVal = null;
        StringBuilder tempName = null;

        // get the print prop values

        Properties props = new Properties();
        props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd"));
        props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("address", demographic.getAddress());
        props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince());
        props.setProperty("postalCode", demographic.getPostal());
        props.setProperty("credHeading", "MyOscar User Account Details");
        props.setProperty("username", "Username: " + username);
        props.setProperty("password", "Password: " + password);
        //Temporary - the intro will change to be dynamic
        props.setProperty("intro",
                "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service.");

        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        Rectangle pageSize = PageSize.LETTER;

        document.setPageSize(pageSize);
        document.open();

        // create a reader for a certain document
        String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/"
                + template;
        PdfReader reader = null;
        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.debug("change path to inside oscar from :" + propFilename);
            reader = new PdfReader("/oscar/form/prop/" + template);
            log.debug("Found template at /oscar/form/prop/" + template);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float width = pSize.getWidth();
        float height = pSize.getHeight();
        log.debug("Width :" + width + " Height: " + height);

        PdfContentByte cb = writer.getDirectContent();
        ColumnText ct = new ColumnText(cb);
        int fontFlags = 0;

        document.newPage();
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

        BaseFont bf; // = normFont;
        String encoding;

        cb.setRGBColorStroke(0, 0, 255);

        String[] fontType;
        for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
            tempName = new StringBuilder(e.nextElement().toString());
            cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *");

            if (cfgVal[4].indexOf(";") > -1) {
                fontType = cfgVal[4].split(";");
                if (fontType[1].trim().equals("italic"))
                    fontFlags = Font.ITALIC;
                else if (fontType[1].trim().equals("bold"))
                    fontFlags = Font.BOLD;
                else if (fontType[1].trim().equals("bolditalic"))
                    fontFlags = Font.BOLDITALIC;
                else
                    fontFlags = Font.NORMAL;
            } else {
                fontFlags = Font.NORMAL;
                fontType = new String[] { cfgVal[4].trim() };
            }

            if (fontType[0].trim().equals("BaseFont.HELVETICA")) {
                fontType[0] = BaseFont.HELVETICA;
                encoding = BaseFont.CP1252; //latin1 encoding
            } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) {
                fontType[0] = BaseFont.HELVETICA_OBLIQUE;
                encoding = BaseFont.CP1252;
            } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) {
                fontType[0] = BaseFont.ZAPFDINGBATS;
                encoding = BaseFont.ZAPFDINGBATS;
            } else {
                fontType[0] = BaseFont.COURIER;
                encoding = BaseFont.CP1252;
            }

            bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);

            // write in a rectangle area
            if (cfgVal.length >= 9) {
                Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags);
                ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()),
                        (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()),
                        (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()),
                        (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT
                                        : Element.ALIGN_CENTER)));

                ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font));
                ct.go();
                continue;
            }

            // draw line directly
            if (tempName.toString().startsWith("__$line")) {
                cb.setRGBColorStrokeF(0f, 0f, 0f);
                cb.setLineWidth(Float.parseFloat(cfgVal[4].trim()));
                cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim()));
                cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim()));
                // stroke the lines
                cb.stroke();
                // write text directly

            } else if (tempName.toString().startsWith("__")) {
                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            } else if (tempName.toString().equals("forms_promotext")) {
                if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
                    cb.beginText();
                    cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                    cb.showTextAligned(
                            (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                    : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                            : PdfContentByte.ALIGN_CENTER)),
                            OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"),
                            Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())),
                            0);

                    cb.endText();
                }
            } else { // write prop text

                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? ""
                                : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            }
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (document != null)
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:org.pentaho.reporting.libraries.fonts.itext.ITextBuiltInFontRegistry.java

License:Open Source License

private FontFamily createCourierFamily() {
    final DefaultFontFamily fontFamily = new DefaultFontFamily("Courier");
    fontFamily.addFontRecord(new ITextBuiltInFontRecord(fontFamily, BaseFont.COURIER, false, false, false));
    fontFamily.addFontRecord(new ITextBuiltInFontRecord(fontFamily, BaseFont.COURIER_BOLD, true, false, false));
    fontFamily/* w w  w  . j  a v  a2 s .  co m*/
            .addFontRecord(new ITextBuiltInFontRecord(fontFamily, BaseFont.COURIER_OBLIQUE, false, true, true));
    fontFamily.addFontRecord(
            new ITextBuiltInFontRecord(fontFamily, BaseFont.COURIER_BOLDOBLIQUE, true, true, true));
    return fontFamily;
}