一个使用itext导出pdf的例子

来源:互联网 发布:首都国旅网络旗舰店 编辑:程序博客网 时间:2024/05/17 01:22
  1. Document doc = new Document (PageSize.A4);  
  2. PdfWriter.getInstance (doc, new FileOutputStream ("c:/test/pdf/test.pdf"));  
  3. doc.open ();  
  4.   
  5. //标题字体  
  6. BaseFont bfTitle = BaseFont.createFont("STSong-Light",   
  7.   "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  8.   Font titleFont = new Font(bfTitle, 18, Font.NORMAL);  
  9.   
  10.    //内容字体  
  11. BaseFont bfComic = BaseFont.createFont("STSong-Light",   
  12.   "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  13.   Font font = new Font(bfComic, 9, Font.NORMAL);  
  14.     
  15. Paragraph titleP=new Paragraph("儿童信息 Child Information/n/n",titleFont);  
  16. titleP.setAlignment(titleP.ALIGN_CENTER);  
  17. doc.add(titleP);  
  18. //生成4列的表格  
  19. PdfPTable table = new PdfPTable (4);  
  20. table.setWidthPercentage(100);  
  21. table.setWidthPercentage(100);  
  22. table.addCell (new Paragraph ("Children-id",font));  
  23. PdfPCell cell = new PdfPCell (new Paragraph ("09140800002",font));  
  24. cell.setColspan (3);  
  25. table.addCell (cell);  
  26. // 添加第一行  
  27. table.addCell (new Paragraph ("Name(CN)",font));  
  28. table.addCell (new Paragraph ("党宁生",font));  
  29. table.addCell (new Paragraph ("Name(EN)",font));  
  30. table.addCell (new Paragraph ("DANG NING SHENG",font));  
  31.   
  32. //添加第二行  
  33. table.addCell (new Paragraph ("Sex(CN)",font));  
  34. table.addCell (new Paragraph ("男",font));  
  35. table.addCell (new Paragraph ("Sex(EN)",font));  
  36. table.addCell (new Paragraph ("MALE",font));  
  37. //添加第8行  
  38. table.addCell (new Paragraph ("Note",font));  
  39. cell = new PdfPCell (new Paragraph ("儿童资料",font));  
  40. cell.setColspan (3);  
  41. table.addCell (cell);  
  42.   
  43. //添加第9行  
  44. table.addCell (new Paragraph ("Pictures",font));  
  45. Image photo=Image.getInstance("c:/test/pdf/1246588678828.jpg");  
  46. cell = new PdfPCell (photo);  
  47. cell.setColspan (3);  
  48. table.addCell (cell);  
  49.   
  50. for(PdfPRow row:(ArrayList<PdfPRow>)table.getRows()){  
  51.  for(PdfPCell cells:row.getCells()){  
  52.   if(cells!=null){  
  53.    cells.setPadding(10.0f);  
  54.   }  
  55.  }  
  56. }  
  57.   
  58. doc.add (table);  
  59. doc.newPage();  
  60.   
  61. //插入图片  
  62. doc.newPage();  
  63. Image image1 = Image.getInstance ("c:/test/pdf/1246588315281.jpg");  
  64. image1.setAlignment(image1.ALIGN_CENTER);  
  65. image1.scaleToFit( PageSize.A4.getHeight(),PageSize.A4.getWidth());  
  66. doc.add (image1);  
  67.   
  68. doc.close ();