Advertisement
Karlie

JavaBasicsHW1-PrintCards

May 15th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import java.io.FileOutputStream;
  2.  
  3. import com.itextpdf.text.BaseColor;
  4. import com.itextpdf.text.Document;
  5. import com.itextpdf.text.Element;
  6. import com.itextpdf.text.Font;
  7. import com.itextpdf.text.Phrase;
  8. import com.itextpdf.text.Rectangle;
  9. import com.itextpdf.text.pdf.BaseFont;
  10. import com.itextpdf.text.pdf.PdfPCell;
  11. import com.itextpdf.text.pdf.PdfPTable;
  12. import com.itextpdf.text.pdf.PdfWriter;
  13.  
  14. public class PrintCards {
  15.  
  16. public static void main(String[] args) {
  17.  
  18. try {
  19. Document document = new Document();
  20. PdfWriter.getInstance(document, new FileOutputStream(
  21. "DeckOfCards.pdf"));
  22. document.open();
  23.  
  24. String faces[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9",
  25. "10", "J", "Q", "K" };
  26. String suits[] = { "\u2660", "\u2665", "\u2666", "\u2663" };
  27. String faceAndSuit;
  28. int countCells = 0;
  29.  
  30.  
  31. BaseFont bf = BaseFont.createFont("arial.ttf", BaseFont.IDENTITY_H,
  32. BaseFont.EMBEDDED);
  33. Font blackFont = new Font(bf, 10, Font.NORMAL, BaseColor.BLACK);
  34. Font redFont = new Font(bf, 10, Font.NORMAL, BaseColor.RED);
  35. Font currentFont;
  36.  
  37. PdfPTable table = new PdfPTable(8);
  38. table.setWidthPercentage(80);
  39. float[] columnWidths = { 10f, 2f, 10f, 2f, 10f, 2f, 10f, 2f };
  40. table.setWidths(columnWidths);
  41.  
  42. PdfPCell emptyCell = new PdfPCell();
  43. emptyCell.setFixedHeight(30f);
  44. emptyCell.setBorder(Rectangle.NO_BORDER);
  45.  
  46. for (int i = 0; i < suits.length; i++) {
  47. for (int j = 0; j < faces.length; j++) {
  48. switch (i) {
  49. case 1:
  50. case 2:
  51. currentFont = redFont;
  52. break;
  53.  
  54. default:
  55. currentFont = blackFont;
  56. break;
  57. }
  58. faceAndSuit = faces[j] + suits[i];
  59. table.addCell(createAndFormatCell(faceAndSuit, currentFont));
  60. table.addCell(emptyCell);
  61. countCells++;
  62. if (countCells % 4 == 0) {
  63. for (int row = 0; row < columnWidths.length; row++) {
  64. table.addCell(emptyCell);
  65. }
  66. }
  67. }
  68. }
  69. document.add(table);
  70. document.close();
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. }
  75.  
  76. public static PdfPCell createAndFormatCell(String cardFace, Font currentFont) {
  77. PdfPCell cardCell = new PdfPCell(new Phrase(cardFace, currentFont));
  78. cardCell.setFixedHeight(100f);
  79. cardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
  80. cardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  81. return cardCell;
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement