Example usage for com.itextpdf.text.pdf PdfPTable setWidthPercentage

List of usage examples for com.itextpdf.text.pdf PdfPTable setWidthPercentage

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable setWidthPercentage.

Prototype

public void setWidthPercentage(final float widthPercentage) 

Source Link

Document

Sets the width percentage that the table will occupy in the page.

Usage

From source file:org.larz.dom4.editor.ReportGenerator.java

License:Open Source License

public static void generateReport(XtextEditor sourcePage, final Shell shell) {
    final IXtextDocument myDocument = ((XtextEditor) sourcePage).getDocument();
    myDocument.modify(new IUnitOfWork.Void<XtextResource>() {
        @Override//from ww w.j ava  2 s  . c o m
        public void process(XtextResource resource) throws Exception {
            Map<String, Map<String, ModObject>> cellMap = new HashMap<String, Map<String, ModObject>>();

            Dom4Mod dom4Mod = (Dom4Mod) resource.getContents().get(0);
            EList<AbstractElement> elements = dom4Mod.getElements();
            for (AbstractElement element : elements) {
                if (element instanceof SelectArmorById || element instanceof SelectArmorByName) {
                    String name = getSelectArmorname((Armor) element);
                    if (name == null)
                        continue;
                    String id = getArmorid((Armor) element);

                    Map<String, ModObject> map = cellMap.get(ARMOR);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(ARMOR, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Armor) element, modObject.propertyMap);
                } else if (element instanceof NewArmor) {
                    String name = getArmorname((Armor) element);
                    String id = getArmorid((Armor) element);

                    Map<String, ModObject> map = cellMap.get(ARMOR);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(ARMOR, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Armor) element, modObject.propertyMap);
                } else if (element instanceof SelectWeaponById || element instanceof SelectWeaponByName) {
                    String name = getSelectWeaponname((Weapon) element);
                    String id = getWeaponid((Weapon) element);

                    Map<String, ModObject> map = cellMap.get(WEAPONS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(WEAPONS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Weapon) element, modObject.propertyMap);
                } else if (element instanceof NewWeapon) {
                    String name = getWeaponname((Weapon) element);
                    String id = getWeaponid((Weapon) element);

                    Map<String, ModObject> map = cellMap.get(WEAPONS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(WEAPONS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Weapon) element, modObject.propertyMap);
                } else if (element instanceof SelectMonsterById || element instanceof SelectMonsterByName) {
                    String name = getSelectMonstername((Monster) element);
                    String id = getMonsterid((Monster) element);

                    Map<String, ModObject> map = cellMap.get(MONSTERS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(MONSTERS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Monster) element, modObject.propertyMap);
                } else if (element instanceof NewMonster) {
                    String name = getMonstername((Monster) element);
                    String id = getMonsterid((Monster) element);

                    Map<String, ModObject> map = cellMap.get(MONSTERS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(MONSTERS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Monster) element, modObject.propertyMap);
                } else if (element instanceof SelectSpellById || element instanceof SelectSpellByName) {
                    String name = getSelectSpellname((Spell) element);
                    String id = getSpellid((Spell) element);

                    Map<String, ModObject> map = cellMap.get(SPELLS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(SPELLS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Spell) element, modObject.propertyMap);
                } else if (element instanceof NewSpell) {
                    String name = getSpellname((Spell) element);
                    //String id = getSpellid((Spell)element);

                    Map<String, ModObject> map = cellMap.get(SPELLS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(SPELLS, map);
                    }
                    ModObject modObject = map.get(name);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = "" + name;
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(name, modObject);
                    }
                    setPropertyValues((Spell) element, modObject.propertyMap);
                } else if (element instanceof SelectItemById || element instanceof SelectItemByName) {
                    String name = getSelectItemname((Item) element);
                    String id = getItemid((Item) element);

                    Map<String, ModObject> map = cellMap.get(ITEMS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(ITEMS, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Item) element, modObject.propertyMap);
                } else if (element instanceof NewItem) {
                    String name = getItemname((Item) element);
                    //String id = getItemid((Item)element);

                    Map<String, ModObject> map = cellMap.get(ITEMS);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(ITEMS, map);
                    }
                    ModObject modObject = map.get(name);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name;
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(name, modObject);
                    }
                    setPropertyValues((Item) element, modObject.propertyMap);
                } else if (element instanceof SelectSiteById || element instanceof SelectSiteByName) {
                    String name = getSelectSitename((Site) element);
                    String id = getSiteid((Site) element);

                    Map<String, ModObject> map = cellMap.get(SITES);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(SITES, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Site) element, modObject.propertyMap);
                } else if (element instanceof NewSite) {
                    String name = getSitename((Site) element);
                    String id = getSiteid((Site) element);

                    Map<String, ModObject> map = cellMap.get(SITES);
                    if (map == null) {
                        map = new HashMap<String, ModObject>();
                        cellMap.put(SITES, map);
                    }
                    ModObject modObject = map.get(id);
                    if (modObject == null) {
                        modObject = new ModObject();
                        modObject.title = name + " (" + id + ")";
                        modObject.propertyMap = new HashMap<String, PropertyValues>();
                        map.put(id, modObject);
                    }
                    setPropertyValues((Site) element, modObject.propertyMap);
                } else if (element instanceof SelectNation) {
                    //                  String name = getSelectNationname((Nation)element);
                    //                  String id = getNationid((Nation)element);
                    //
                    //                  Map<String, ModObject> map = cellMap.get(NATIONS);
                    //                  if (map == null) {
                    //                     map = new HashMap<String, ModObject>();
                    //                     cellMap.put(NATIONS, map);
                    //                  }
                    //                  ModObject modObject = map.get(id);
                    //                  if (modObject == null) {
                    //                     modObject = new ModObject();
                    //                     modObject.title = name + " (" + id + ")";
                    //                     modObject.propertyMap = new HashMap<String, PropertyValues>();
                    //                     map.put(id, modObject);
                    //                  }
                    //                  setPropertyValues((SelectNation)element, modObject.propertyMap, resource);
                }

            }

            try {
                // step 1
                Document document = new Document(PageSize.LETTER.rotate());
                // step 2
                File tempFile = File.createTempFile("dom4editor", ".pdf");
                tempFile.deleteOnExit();
                FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);

                PdfWriter.getInstance(document, tempFileOutputStream);
                // step 3
                document.open();

                List<Map.Entry<String, Map<String, ModObject>>> cellList = new ArrayList<Map.Entry<String, Map<String, ModObject>>>();
                for (Map.Entry<String, Map<String, ModObject>> innerEntry : cellMap.entrySet()) {
                    cellList.add(innerEntry);
                }
                Collections.sort(cellList, new Comparator<Map.Entry<String, Map<String, ModObject>>>() {
                    @Override
                    public int compare(Map.Entry<String, Map<String, ModObject>> o1,
                            Map.Entry<String, Map<String, ModObject>> o2) {
                        return o1.getKey().compareTo(o2.getKey());
                    }
                });

                for (Map.Entry<String, Map<String, ModObject>> entry : cellList) {
                    PdfPTable table = new PdfPTable(1);
                    table.setWidthPercentage(100f);

                    PdfPCell cell = new PdfPCell(new Phrase(entry.getKey(), TITLE));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    cell.setFixedHeight(26f);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
                    table.addCell(cell);
                    table.setHeaderRows(1);

                    List<Map.Entry<String, ModObject>> list = new ArrayList<Map.Entry<String, ModObject>>();
                    for (Map.Entry<String, ModObject> innerEntry : entry.getValue().entrySet()) {
                        list.add(innerEntry);
                    }

                    Collections.sort(list, new Comparator<Map.Entry<String, ModObject>>() {
                        @Override
                        public int compare(Map.Entry<String, ModObject> o1, Map.Entry<String, ModObject> o2) {
                            return o1.getValue().title.compareTo(o2.getValue().title);
                        }
                    });

                    PdfPTable propertyTable = null;
                    if (entry.getKey().equals(ARMOR)) {
                        propertyTable = getTable(new String[] { "name", "type", "prot", "def", "enc", "rcost" },
                                new String[] { "Name", "Type", "Prot", "Def", "Enc", "Rcost" },
                                new ValueTranslator[] { null, new ValueTranslator() {
                                    @Override
                                    public String translate(String value) {
                                        if (value == null)
                                            return null;
                                        if (value.equals("4"))
                                            return "Shield";
                                        if (value.equals("5"))
                                            return "Body Armor";
                                        if (value.equals("6"))
                                            return "Helmet";
                                        return "Unknown";
                                    }
                                }, null, null, null, null }, null, list);
                        propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1 });
                    }
                    if (entry.getKey().equals(WEAPONS)) {
                        propertyTable = getTable(
                                new String[] { "name", "dmg", "att", "nratt", "def", "len", "range", "ammo",
                                        "rcost" },
                                new String[] { "Name", "Dmg", "Att", "Nratt", "Def", "Len", "Range", "Ammo",
                                        "Rcost" },
                                null, null, list);
                        propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1 });
                    }
                    if (entry.getKey().equals(MONSTERS)) {
                        propertyTable = getTable(
                                new String[] { "name", "hp", "prot", "MOVE", "size", "ressize", "str", "enc",
                                        "att", "def", "prec", "mr", "mor", "gcost", "rcost" },
                                new String[] { "Name", "HP", "Prot", "Move", "Size", "Rsize", "Str", "Enc",
                                        "Att", "Def", "Prec", "MR", "Mor", "Gcost", "Rcost" },
                                null, new ValueCombiner[] { null, null, null, new ValueCombiner() {
                                    @Override
                                    public String translate(String[] value) {
                                        if (value[0] == null && value[1] == null)
                                            return null;
                                        return value[0] + "/" + value[1];
                                    }

                                    @Override
                                    public String[] getNeededColumns() {
                                        return new String[] { "mapmove", "ap" };
                                    }
                                }, null, null, null, null, null, null, null, null, null, null, null }, list);
                        propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });
                    }
                    if (entry.getKey().equals(ITEMS)) {
                        propertyTable = getTable(
                                new String[] { "name", "constlevel", "PATH", "type", "weapon", "armor" },
                                new String[] { "Name", "Constlevel", "Path Req", "Type", "Weapon", "Armor" },
                                new ValueTranslator[] { null, null, null, new ValueTranslator() {
                                    @Override
                                    public String translate(String value) {
                                        if (value == null)
                                            return null;
                                        if (value.equals("1"))
                                            return "1-h Weapon";
                                        if (value.equals("2"))
                                            return "2-h Weapon";
                                        if (value.equals("3"))
                                            return "Missile Weapon";
                                        if (value.equals("4"))
                                            return "Shield";
                                        if (value.equals("5"))
                                            return "Body Armor";
                                        if (value.equals("6"))
                                            return "Helmet";
                                        if (value.equals("7"))
                                            return "Boots";
                                        if (value.equals("8"))
                                            return "Misc";
                                        return "Unknown";
                                    }
                                }, null, null }, new ValueCombiner[] { null, null, new ValueCombiner() {
                                    @Override
                                    public String translate(String[] value) {
                                        if (value[0] == null && value[1] == null && value[2] == null
                                                && value[3] == null)
                                            return null;
                                        StringBuffer buf = new StringBuffer();
                                        if (value[0] != null && !value[0].equals("null")) {
                                            buf.append(getPathName(Integer.parseInt(value[0])) + value[1]);
                                        }
                                        if (value[2] != null && !value[2].equals("null")
                                                && !value[2].equals("-1")) {
                                            buf.append(getPathName(Integer.parseInt(value[2])) + value[3]);
                                        }
                                        return buf.toString();
                                    }

                                    @Override
                                    public String[] getNeededColumns() {
                                        return new String[] { "mainpath", "mainlevel", "secondarypath",
                                                "secondarylevel" };
                                    }
                                }, null, null, null }, list);
                        propertyTable.setWidths(new float[] { 2.5f, 1, 1, 1, 2.5f, 2.5f });
                    }
                    if (entry.getKey().equals(SPELLS)) {
                        propertyTable = getTable(
                                new String[] { "name", "school", "researchlevel", "aoe", "damage", "effect",
                                        "fatiguecost", "nreff", "range", "precision", "spec", "nextspell" },
                                new String[] { "Name", "School", "Research", "AOE", "Damage", "Effect",
                                        "Fatigue", "Nreff", "Range", "Precision", "Spec", "Nextspell" },
                                null, null, list);
                        propertyTable.setWidths(new float[] { 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });
                    }
                    if (entry.getKey().equals(NATIONS)) {
                        propertyTable = getTable(new String[] { "name", "startsite1", "startsite2",
                                "startsite3", "startsite4", "era", "startfort" }, list);
                        propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1 });
                    }
                    if (entry.getKey().equals(SITES)) {
                        propertyTable = getTable(
                                new String[] { "name", "path", "level", "rarity", "loc", "homemon", "homecom",
                                        "gold", "res" },
                                new String[] { "Name", "Path", "Level", "Rarity", "Loc", "Homemon", "Homecom",
                                        "Gold", "Res" },
                                new ValueTranslator[] { null, new ValueTranslator() {
                                    @Override
                                    public String translate(String value) {
                                        if (value == null)
                                            return null;
                                        if (value.equals("0"))
                                            return "Fire";
                                        if (value.equals("1"))
                                            return "Air";
                                        if (value.equals("2"))
                                            return "Water";
                                        if (value.equals("3"))
                                            return "Earth";
                                        if (value.equals("4"))
                                            return "Astral";
                                        if (value.equals("5"))
                                            return "Death";
                                        if (value.equals("6"))
                                            return "Nature";
                                        if (value.equals("7"))
                                            return "Blood";
                                        return "Unknown";
                                    }
                                }, null, null, null, null, null, null, null }, null, list);
                        propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1 });
                    }
                    PdfPCell innerCell = new PdfPCell();
                    innerCell.addElement(propertyTable);
                    innerCell.setBorder(PdfPCell.NO_BORDER);
                    innerCell.setHorizontalAlignment(Element.ALIGN_LEFT);

                    table.addCell(innerCell);
                    document.add(table);
                    document.newPage();
                }
                document.close();

                tempFileOutputStream.flush();
                tempFileOutputStream.close();

                Program pdfViewer = Program.findProgram("pdf");
                if (pdfViewer != null) {
                    pdfViewer.execute(tempFile.getAbsolutePath());
                } else {
                    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
                    dialog.setFilterExtensions(new String[] { "*.pdf" });
                    if (dialog.open() != null) {
                        FileInputStream from = null;
                        FileOutputStream to = null;
                        try {
                            String filterPath = dialog.getFilterPath();
                            String name = dialog.getFileName();

                            from = new FileInputStream(new File(tempFile.getAbsolutePath()));
                            to = new FileOutputStream(new File(filterPath + File.separator + name));
                            byte[] buffer = new byte[4096];
                            int bytesRead;

                            while ((bytesRead = from.read(buffer)) != -1) {
                                to.write(buffer, 0, bytesRead); // write
                            }
                        } finally {
                            if (from != null) {
                                from.close();
                            }
                            if (to != null) {
                                to.close();
                            }
                        }
                    }
                }

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

From source file:org.larz.dom4.editor.ReportGenerator.java

License:Open Source License

private static PdfPTable getTable(String[] columns, String[] columnNames, ValueTranslator[] trans,
        ValueCombiner[] combine, List<Map.Entry<String, ModObject>> list) {
    PdfPTable table = new PdfPTable(columns.length);
    table.setWidthPercentage(100f);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    for (String col : columnNames) {
        PdfPCell c = new PdfPCell(new Phrase(col, SUBTITLE));
        c.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(c);//from w  ww. jav a  2s . c o m
    }
    table.setHeaderRows(1);

    for (Map.Entry<String, ModObject> innerEntry : list) {
        String name = innerEntry.getValue().title;
        Map<String, PropertyValues> map = innerEntry.getValue().propertyMap;

        List<Map.Entry<String, PropertyValues>> list2 = new ArrayList<Map.Entry<String, PropertyValues>>();
        for (Map.Entry<String, PropertyValues> innerEntry2 : map.entrySet()) {
            list2.add(innerEntry2);
        }
        Collections.sort(list2, new Comparator<Map.Entry<String, PropertyValues>>() {
            @Override
            public int compare(Map.Entry<String, PropertyValues> o1, Map.Entry<String, PropertyValues> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        if (list2.size() == 0)
            continue;

        PdfPCell[] cells = new PdfPCell[columns.length];
        cells[0] = new PdfPCell();
        cells[0].addElement(new Phrase(name, BOLD_TEXT));

        for (int i = 1; i < cells.length; i++) {
            cells[i] = new PdfPCell();
            if (combine != null && combine[i] != null) {
                String[] neededCols = combine[i].getNeededColumns();
                String[] oldValues = new String[neededCols.length];
                String[] newValues = new String[neededCols.length];
                for (int j = 0; j < neededCols.length; j++) {
                    for (Map.Entry<String, PropertyValues> entry : list2) {
                        if (entry.getKey().equals(neededCols[j])) {
                            oldValues[j] = entry.getValue().oldValue;
                            newValues[j] = entry.getValue().newValue;
                            break;
                        }
                    }
                }
                // Put old values into null new values
                boolean hasNew = false;
                for (int k = 0; k < newValues.length; k++) {
                    if (newValues[k] != null) {
                        hasNew = true;
                        break;
                    }
                }
                if (hasNew) {
                    for (int k = 0; k < newValues.length; k++) {
                        if (newValues[k] == null) {
                            newValues[k] = oldValues[k];
                        }
                    }
                }
                String newValue = combine[i].translate(newValues);
                String oldValue = combine[i].translate(oldValues);
                if (newValue != null) {
                    Phrase phrase = new Phrase();
                    phrase.add(new Chunk(newValue, BOLD_TEXT));
                    if (oldValue != null) {
                        phrase.add(new Chunk(" (" + oldValue + ")", TEXT));
                    }
                    cells[i].addElement(phrase);
                } else if (oldValue != null) {
                    cells[i].addElement(new Phrase(oldValue, TEXT));
                }
            } else {
                for (Map.Entry<String, PropertyValues> entry : list2) {
                    if (entry.getKey().equals(columns[i])) {
                        String oldValue = entry.getValue().oldValue;
                        String newValue = entry.getValue().newValue;
                        if (trans != null && trans.length > i && trans[i] != null) {
                            oldValue = trans[i].translate(oldValue);
                            newValue = trans[i].translate(newValue);
                        }
                        if (newValue != null) {
                            Phrase phrase = new Phrase();
                            phrase.add(new Chunk(newValue, BOLD_TEXT));
                            if (oldValue != null && !oldValue.equals("null")) {
                                phrase.add(new Chunk(" (" + oldValue + ")", TEXT));
                            }
                            cells[i].addElement(phrase);
                        } else if (oldValue != null && !oldValue.equals("null")) {
                            cells[i].addElement(new Phrase(oldValue, TEXT));
                        }
                        break;
                    }
                }
            }
        }

        for (PdfPCell cell : cells) {
            table.addCell(cell);
        }
    }
    return table;
}

From source file:org.me.modelos.PDFHelper.java

public void tablaToPdf(JTable jTable, File pdfNewFile, String title) {
    try {/*from   w ww .ja va  2  s.com*/
        Font subCategoryFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
        Document document = new Document(PageSize.LETTER.rotate());
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));
        } catch (FileNotFoundException fileNotFoundException) {
            Message.showErrorMessage(fileNotFoundException.getMessage());
        }

        writer.setBoxSize("art", new Rectangle(150, 10, 700, 580));
        writer.setPageEvent(new HeaderFooterPageEvent());
        document.open();
        document.addTitle(title);

        document.addSubject("Reporte");
        document.addKeywords("reportes, gestion, pdf");
        document.addAuthor("Gestion de Proyectos de software");
        document.addCreator("gestion de proyectos");

        Paragraph parrafo = new Paragraph(title, subCategoryFont);

        PdfPTable table = new PdfPTable(jTable.getColumnCount());
        table.setWidthPercentage(100);
        PdfPCell columnHeader;

        for (int column = 0; column < jTable.getColumnCount(); column++) {
            Font font = new Font(Font.FontFamily.HELVETICA);
            font.setColor(255, 255, 255);
            columnHeader = new PdfPCell(new Phrase(jTable.getColumnName(column), font));
            columnHeader.setHorizontalAlignment(Element.ALIGN_LEFT);
            columnHeader.setBackgroundColor(new BaseColor(96, 125, 139));
            table.addCell(columnHeader);
        }
        table.getDefaultCell().setBackgroundColor(new BaseColor(255, 255, 255));
        table.setHeaderRows(1);
        BaseColor verdad = new BaseColor(255, 255, 255);
        BaseColor falso = new BaseColor(214, 230, 244);
        boolean bandera = false;
        for (int row = 0; row < jTable.getRowCount(); row++) {

            for (int column = 0; column < jTable.getColumnCount(); column++) {

                if (bandera) {
                    table.getDefaultCell().setBackgroundColor(verdad);
                } else {
                    table.getDefaultCell().setBackgroundColor(falso);
                }
                table.addCell(jTable.getValueAt(row, column).toString());
                bandera = !bandera;
            }

        }

        parrafo.add(table);
        document.add(parrafo);
        document.close();
        //JOptionPane.showMessageDialog(null, "Se ha creado el pdf en " + pdfNewFile.getPath(),
        //        "RESULTADO", JOptionPane.INFORMATION_MESSAGE);
    } catch (DocumentException documentException) {
        System.out.println("Se ha producido un error " + documentException);
        JOptionPane.showMessageDialog(null, "Se ha producido un error" + documentException, "ERROR",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.openlmis.web.view.pdf.requisition.RequisitionPdfModel.java

License:Open Source License

private PdfPTable prepareTable(List<? extends Column> visibleColumns) throws DocumentException {
    java.util.List<Integer> widths = new ArrayList<>();
    for (Column column : visibleColumns) {
        widths.add(column.getColumnWidth());
    }// w  w  w  .  j  ava 2  s.  c om
    PdfPTable table = new PdfPTable(widths.size());

    table.setWidths(ArrayUtils.toPrimitive(widths.toArray(new Integer[widths.size()])));
    table.getDefaultCell().setBackgroundColor(HEADER_BACKGROUND);
    table.getDefaultCell().setPadding(CELL_PADDING);
    table.setWidthPercentage(WIDTH_PERCENTAGE);
    table.setSpacingBefore(TABLE_SPACING);
    table.setHeaderRows(2);
    table.setFooterRows(1);
    setTableHeader(table, visibleColumns);
    setBlankFooter(table, visibleColumns.size());
    return table;
}

From source file:org.openlmis.web.view.pdf.requisition.RequisitionPdfModel.java

License:Open Source License

private PdfPTable prepareRequisitionHeaderTable() throws DocumentException {
    int[] columnWidths = { 160, 160, 160, 160, 160 };
    PdfPTable table = new PdfPTable(columnWidths.length);
    table.setWidths(columnWidths);/* w ww  .ja  v  a2 s  . c om*/
    table.getDefaultCell().setBackgroundColor(HEADER_BACKGROUND);
    table.getDefaultCell().setPadding(10);
    table.getDefaultCell().setBorder(0);
    table.setWidthPercentage(WIDTH_PERCENTAGE);
    table.setSpacingBefore(TABLE_SPACING);
    table.setHeaderRows(1);
    return table;
}

From source file:org.openlmis.web.view.pdf.requisition.RequisitionPdfModel.java

License:Open Source License

public PdfPTable getSummary() throws DocumentException {
    this.requisition.fillFullSupplyCost();
    this.requisition.fillNonFullSupplyCost();

    DecimalFormat formatter = new DecimalFormat("#,##0.00");

    PdfPTable summaryTable = new PdfPTable(2);
    summaryTable.setWidths(new int[] { 30, 20 });
    summaryTable.setSpacingBefore(TABLE_SPACING);
    summaryTable.setWidthPercentage(40);
    summaryTable.setHorizontalAlignment(0);

    PdfPCell summaryHeaderCell = headingCell(messageService.message("label.summary"));
    summaryHeaderCell.setColspan(2);//from   w w w .j a v a  2  s .com
    summaryHeaderCell.setPadding(10);
    summaryHeaderCell.setBorder(0);
    summaryTable.addCell(summaryHeaderCell);

    boolean showBudget = !requisition.isEmergency() && requisition.getProgram().getBudgetingApplies();
    if (showBudget) {
        summaryTable.addCell(summaryCell(textCell(messageService.message("label.allocated.budget"))));
        PdfPCell allocatedBudgetCell = requisition.getAllocatedBudget() != null
                ? numberCell(messageService.message(LABEL_CURRENCY_SYMBOL)
                        + formatter.format(new Money(requisition.getAllocatedBudget()).toDecimal()))
                : numberCell(messageService.message("msg.budget.not.allocated"));
        summaryTable.addCell(summaryCell(allocatedBudgetCell));
    }
    summaryTable.addCell(summaryCell(textCell(messageService.message("label.total.cost.full.supply.items"))));
    summaryTable.addCell(summaryCell(numberCell(messageService.message(LABEL_CURRENCY_SYMBOL)
            + formatter.format(requisition.getFullSupplyItemsSubmittedCost().toDecimal()))));
    summaryTable
            .addCell(summaryCell(textCell(messageService.message("label.total.cost.non.full.supply.items"))));
    summaryTable.addCell(summaryCell(numberCell(messageService.message(LABEL_CURRENCY_SYMBOL)
            + formatter.format(requisition.getNonFullSupplyItemsSubmittedCost().toDecimal()))));
    summaryTable.addCell(summaryCell(textCell(messageService.message("label.total.cost"))));
    summaryTable.addCell(summaryCell(numberCell(messageService.message(LABEL_CURRENCY_SYMBOL)
            + formatter.format(this.getTotalCost(requisition).toDecimal()).toString())));
    if (showBudget && requisition.getAllocatedBudget() != null
            && (requisition.getAllocatedBudget().compareTo(this.getTotalCost(requisition).getValue()) == -1)) {
        summaryTable.addCell(summaryCell(textCell(messageService.message("msg.cost.exceeds.budget"))));
        summaryTable.addCell(summaryCell(textCell(" ")));
    }

    summaryTable.addCell(summaryCell(textCell(" ")));
    summaryTable.addCell(summaryCell(textCell(" ")));
    summaryTable.addCell(summaryCell(textCell(" ")));
    summaryTable.addCell(summaryCell(textCell(" ")));

    fillAuditFields(summaryTable);
    return summaryTable;
}

From source file:org.openmrs.module.laboratorymanagement.db.hibernate.LaboratoryDAOimpl.java

License:Open Source License

public void exportPatientReportToPDF(HttpServletRequest request, HttpServletResponse response,
        Map<ConceptName, List<Object[]>> mappedLabExam, String filename, String title, int patientId)
        throws DocumentException, IOException {

    Document document = new Document();
    Patient patient = Context.getPatientService().getPatient(patientId);
    // List<PatientBill> patientBills =
    // (List<PatientBill>)request.getAttribute("reportedPatientBillsPrint");

    /*//from  ww w .  j av  a 2  s.c om
     * PatientBill pb = null;
     * 
     * pb = Context.getService(BillingService.class).getPatientBill(
     * Integer.parseInt(request.getParameter("patientBills")));
     */
    /*
     * String filename = pb.getBeneficiary().getPatient().getPersonName()
     * .toString().replace(" ", "_"); filename =
     * pb.getBeneficiary().getPolicyIdNumber().replace(" ", "_") + "_" +
     * filename + ".pdf";
     */
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "report"); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(0, 0, 2382, 3369));
    writer.setBoxSize("art", PageSize.A4);

    HeaderFooterMgt event = new HeaderFooterMgt();
    writer.setPageEvent(event);

    document.open();
    document.setPageSize(PageSize.A4);
    // document.setPageSize(new Rectangle(0, 0, 2382, 3369));

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().toString());// the name of the author

    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.COURIER, 10.0f, Font.ITALIC));

    // Report title
    Chunk chk = new Chunk("Printed on : " + (new SimpleDateFormat("dd-MMM-yyyy").format(new Date())));
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    Paragraph todayDate = new Paragraph();
    todayDate.setAlignment(Element.ALIGN_RIGHT);
    todayDate.add(chk);
    document.add(todayDate);
    document.add(fontTitle.process("REPUBLIQUE DU RWANDA\n"));
    document.add(fontTitle.process("POLICE NATIONALE\n"));
    document.add(fontTitle.process("KACYIRU POLICE HOSPITAL\n"));
    document.add(fontTitle.process("B.P. 6183 KIGALI\n"));
    document.add(fontTitle.process("Tl : 584897\n"));
    document.add(fontTitle.process("E-mail : medical@police.gov.rw"));
    // End Report title

    document.add(new Paragraph("\n"));
    chk = new Chunk("Laboratory results");
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    chk.setUnderline(0.2f, -2f);
    Paragraph pa = new Paragraph();
    pa.add(chk);
    pa.setAlignment(Element.ALIGN_CENTER);
    document.add(pa);
    document.add(new Paragraph("\n"));

    document.add(fontTitle.process("Family Name: " + patient.getFamilyName() + "\n"));
    document.add(fontTitle.process("Given name: " + patient.getGivenName() + "\n"));
    document.add(fontTitle.process("Age: " + patient.getAge() + "\n"));

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.COURIER, 9, Font.ITALIC));
    // Table of identification;
    PdfPTable table = null;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    // tableHeader.addCell(table);

    // document.add(tableHeader);

    document.add(new Paragraph("\n"));

    // Table of lab report items;
    float[] colsWidth = { 6f, 3f, 6f };
    table = new PdfPTable(colsWidth);
    table.setWidthPercentage(100f);
    BaseColor bckGroundTitle = new BaseColor(170, 170, 170);
    BaseColor bckGroundTitl = new BaseColor(Color.yellow);

    // table Header
    PdfPCell cell = new PdfPCell(fontTitleSelector.process("Exam"));

    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Result"));
    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Normal Range"));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);
    /*
     * cell = new PdfPCell(fontTitleSelector.process("Date "));
     * cell.setBackgroundColor(bckGroundTitle); table.addCell(cell);
     */

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    // empty row
    FontSelector fontTotals = new FontSelector();
    fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

    // ===========================================================
    for (ConceptName cptName : mappedLabExam.keySet()) {

        cell = new PdfPCell(fontTitleSelector.process("" + cptName));
        cell.setBackgroundColor(bckGroundTitl);

        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);

        List<Object[]> labExamHistory = mappedLabExam.get(cptName);
        for (Object[] labExam : labExamHistory) {
            // table Header
            // Object[] labe = listOflabtest.get(i);
            Obs ob = (Obs) labExam[0];
            cell = new PdfPCell(fontTitleSelector.process("" + ob.getConcept().getName()));

            table.addCell(cell);
            if (ob.getConcept().getDatatype().isNumeric()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueNumeric()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isCoded()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueCoded().getName()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isText()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueText()));
                table.addCell(cell);

            }

            cell = new PdfPCell(fontTitleSelector.process("" + (labExam[1] != null ? labExam[1] : "-")));
            table.addCell(cell);

            fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

            // empty row
            // FontSelector fontTotals = new FontSelector();
            fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

        }

    }

    cell = new PdfPCell(fontTitleSelector.process("Names, Signature et Stamp of Lab Chief\n"
            //+ Context.getAuthenticatedUser().getPersonName()));
            + Context.getUserService().getUser(140).getPersonName()));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    // ================================================================
    table.addCell(cell);

    document.add(table);

    // Table of signatures;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    cell = new PdfPCell(fontTitleSelector.process(" "));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(
            "Names, Signature and  Stamp of Provider\n" + Context.getAuthenticatedUser().getPersonName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    document.add(table);
    document.close();

    document.close();
}

From source file:org.openmrs.module.tracpatienttransfer.util.FileExporter.java

License:Open Source License

/**
 * @param request/*  w  w  w  .  j  a va  2s.  c o  m*/
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToPDF(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {

    SimpleDateFormat sdf = Context.getDateFormat();

    Document document = new Document();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    float[] colsWidth = { 1.6f, 2.7f, 2.7f, 8f, 10.5f, 4f, 5f, 7.5f };//, 9.3f };
    PdfPTable table = new PdfPTable(colsWidth); // column number

    HeaderFooter event = new HeaderFooter(table);
    writer.setPageEvent(event);

    document.setPageSize(PageSize.A4.rotate());
    document.open();

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().getFamilyName() + " "
            + Context.getAuthenticatedUser().getPersonName().getGivenName());// the name of the author

    ObsService os = Context.getObsService();
    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(
            fontTitle.process(MohTracUtil.getMessage("tracpatienttransfer.report", null) + "    : " + title));// Report title
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
            + " : " + sdf.format(new Date())));// Report date
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
            + " : " + Context.getAuthenticatedUser().getPersonName()));// Report
    // author
    document.add(new Paragraph("\n"));

    Paragraph para = new Paragraph("" + title.toUpperCase());
    para.setAlignment(Element.ALIGN_CENTER);
    para.setFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(para);

    table.setWidthPercentage(100.0f);

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.HELVETICA, 8, Font.BOLD));

    // top line of table
    for (int i = 0; i < 8; i++) {
        PdfPCell pdfPCell = new PdfPCell(fontTitleSelector.process(" "));
        pdfPCell.setBorder(PdfPCell.BOTTOM);
        table.addCell(pdfPCell);
    }

    boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

    // table Header
    PdfPCell cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.number")));
    cell.setBorder(Rectangle.LEFT);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(Context.getPatientService()
            .getPatientIdentifierType(TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
            .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(Context.getPatientService()
                    .getPatientIdentifierType(
                            TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    if (hasRoleToViewPatientsNames) {
        cell = new PdfPCell(
                fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.names")));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
    }

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.reasonofexit")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.exitwhen")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(ContextProvider.getMessage("Encounter.provider")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.report.location")));
    cell.setBorder(Rectangle.RIGHT);
    table.addCell(cell);

    //      cell = new PdfPCell(fontTitleSelector
    //            .process("Resumed? (reason - by who?)"));
    //      cell.setBorder(Rectangle.RIGHT);
    //      table.addCell(cell);

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    // empty row
    FontSelector fontEmptyCell = new FontSelector();
    fontEmptyCell.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    int ids = 0;

    for (Integer obsId : res) {
        Obs obs = os.getObs(obsId);
        Integer patientId = obs.getPersonId();
        ids += 1;

        cell = new PdfPCell(fontselector.process(ids + "."));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String tracnetId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(tracnetId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String localIdentifierTypeId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(
                patientId, TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(localIdentifierTypeId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        if (hasRoleToViewPatientsNames) {
            String names = TransferOutInPatientTag.getPersonNames(patientId);
            cell = new PdfPCell(fontselector.process(names + ""));
            if (ids == 1)
                cell.setBorder(Rectangle.TOP);
            else
                cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }

        String conceptValue = TransferOutInPatientTag.conceptValueByObs(obs);

        conceptValue += ((obs.getValueCoded().getConceptId()
                .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                        : (obs.getValueCoded().getConceptId()
                                .intValue() == TransferOutInPatientConstant.PATIENT_DEAD)
                                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                                TransferOutInPatientConstant.CAUSE_OF_DEATH) + ")"
                                        : "");

        cell = new PdfPCell(fontselector.process(conceptValue));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        cell = new PdfPCell(fontselector.process(sdf.format(obs.getObsDatetime())));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        /*
         * cell=newPdfPCell(fontselector.process(TransferOutInPatientTag.
         * getProviderByObs(obs))); if(ids==1)
         * cell.setBorder(Rectangle.TOP); else
         * cell.setBorder(Rectangle.NO_BORDER);
         */table.addCell(cell);

        cell = new PdfPCell(fontselector.process(obs.getLocation().getName()));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        //         cell = new PdfPCell(fontselector.process(TransferOutInPatientTag
        //               .obsVoidedReason(obs)));
        //         if (ids == 1)
        //            cell.setBorder(Rectangle.TOP);
        //         else
        //            cell.setBorder(Rectangle.NO_BORDER);
        //         table.addCell(cell);
    }

    document.add(table);
    document.close();

    log.info("pdf file created");
}

From source file:org.oscarehr.fax.util.PdfCoverPageCreator.java

License:Open Source License

public byte[] createCoverPage() {

    Document document = new Document();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {/*from ww  w  .j  a  v  a 2 s.  com*/

        PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
        document.open();

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(95);

        PdfPCell cell = new PdfPCell(table);
        cell.setBorder(0);
        cell.setPadding(3);
        cell.setColspan(1);
        table.addCell(cell);

        ClinicDAO clinicDao = SpringUtils.getBean(ClinicDAO.class);
        Clinic clinic = clinicDao.getClinic();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bf, 28, Font.BOLD);
        Font infoFont = new Font(bf, 12, Font.NORMAL);

        if (clinic != null) {

            cell = new PdfPCell(new Phrase(
                    String.format("%s\n %s, %s, %s %s", clinic.getClinicName(), clinic.getClinicAddress(),
                            clinic.getClinicCity(), clinic.getClinicProvince(), clinic.getClinicPostal()),
                    headerFont));
        } else {

            cell = new PdfPCell(new Phrase("OSCAR", headerFont));

        }

        cell.setPaddingTop(100);
        cell.setPaddingLeft(25);
        cell.setPaddingBottom(25);
        cell.setBorderWidthBottom(1);
        table.addCell(cell);

        PdfPTable infoTable = new PdfPTable(1);
        cell = new PdfPCell(new Phrase(note, infoFont));
        cell.setPaddingTop(25);
        cell.setPaddingLeft(25);
        infoTable.addCell(cell);
        table.addCell(infoTable);

        document.add(table);

    } catch (DocumentException e) {

        MiscUtils.getLogger().error("PDF COVER PAGE ERROR", e);
        return new byte[] {};

    } catch (IOException e) {

        MiscUtils.getLogger().error("PDF COVER PAGE ERROR", e);
        return new byte[] {};

    } finally {
        document.close();
    }

    return os.toByteArray();
}

From source file:org.patientview.radar.service.impl.PdfDocumentDataBuilder.java

License:Open Source License

public byte[] build(DocumentData documentData) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {// www.ja  va2  s  .com
        Document document = new Document(PageSize.A4, 0, 0, 20, 20);

        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        writer.setFullCompression();
        writer.setLinearPageMode();

        document.open();

        PdfPTable table = new PdfPTable(documentData.getHeaders().size());
        table.setWidthPercentage(90);

        // create the header cells
        for (String s : documentData.getHeaders()) {
            table.addCell(createHeadingCell(s));
        }

        // create the data row cells
        for (List<String> l : documentData.getRows()) {
            for (String s : l) {
                table.addCell(createRowCell(s));
            }
        }

        document.add(table);

        document.close();
    } catch (Exception e) {
        LOGGER.error("Could not build pdf " + e.getMessage());
    }
    return outputStream.toByteArray();
}