Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import com.itextpdf.text.BaseColor;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.FontFactory;
- import com.itextpdf.text.Phrase;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.FontSelector;
- import com.itextpdf.text.pdf.PdfPCell;
- import com.itextpdf.text.pdf.PdfPTable;
- import com.itextpdf.text.pdf.PdfWriter;
- public class Ex09_GeneratePdfDeckOfCard {
- public static void main(String[] args) throws FileNotFoundException,
- DocumentException {
- Document document = new Document();
- PdfWriter.getInstance(document, new FileOutputStream("TestPdf.pdf"));
- // Create pdf file
- document.open(); // Open stream
- PdfPTable table = createTable1();
- table.setSpacingBefore(5);
- table.setSpacingAfter(5);
- document.add(table);
- document.close(); // Close stream
- }
- // Create font for cards
- public static Phrase ColoredText(String text, String color) {
- FontSelector selector = new FontSelector();
- Font usedColor;
- if (color == "red") {
- usedColor = FontFactory.getFont(
- "/usr/share/fonts/truetype/msttcorefonts/arial.ttf",
- BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- // if doesn't work find arial.ttf in your computer
- usedColor.setColor(BaseColor.RED);
- }
- else {
- usedColor = FontFactory.getFont(
- "/usr/share/fonts/truetype/msttcorefonts/arial.ttf",
- BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- usedColor.setColor(BaseColor.BLACK);
- }
- selector.addFont(usedColor);
- Phrase ph = selector.process(text);
- return ph;
- }
- public static PdfPTable createTable1() throws DocumentException {
- // Table size
- PdfPTable table = new PdfPTable(4);
- table.setWidthPercentage(500 / 5.23f);
- table.getDefaultCell().setFixedHeight(100);
- table.setWidths(new int[] { 3, 3, 3, 3 });
- PdfPCell cell;
- cell = new PdfPCell(new Phrase("Cards"));
- cell.setColspan(4); // number of cols
- table.addCell(cell);
- cell.setRowspan(13); // number of rols
- String[] cardsNameStrings = new String[] { "Ace", "2", "3", "4", "5",
- "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
- String[] cardsTypeStrings = new String[] { "\u2666", "\u2665",
- "\u2660", "\u2663" };
- // Imput data
- for (int name = 0; name < cardsNameStrings.length; name++) {
- for (int type = 0; type < cardsTypeStrings.length; type++) {
- if (type <= 1) {
- table.addCell(ColoredText(cardsNameStrings[name]
- + cardsTypeStrings[type], "red"));
- } else {
- table.addCell(ColoredText(cardsNameStrings[name]
- + cardsTypeStrings[type], "black"));
- }
- }
- }
- return table;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement