package com.sipai.controller.base; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontProvider; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; import com.sipai.tools.CommUtil; import java.io.ByteArrayInputStream; import java.net.MalformedURLException; import java.nio.charset.Charset; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; public class PDFFileUtil { Document document = null;// 建立一个Document对象 /* private static Font headFont ; private static Font keyFont ; private static Font nbspFont; private static Font textfont_H ; private static Font textfont_B ; private static Font textfont_13; private static Font textfont_12; private static Font textfont_11; private static Font textfont_10; private static Font textfont_9; private static Font textfont_8; private static Font textfont_7; private static Font textfont_6; int maxWidth = 520;*/ public void createPDF(String outputPath, String xmlStr) { try { Document document = new Document(); document.setPageSize(PageSize.A4);// 设置页面大小 PdfWriter mPdfWriter = PdfWriter. getInstance(document, new FileOutputStream(outputPath)); document.open(); ByteArrayInputStream bin = new ByteArrayInputStream(xmlStr.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new ChinaFontProvide()); /*BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont); document.add(new Paragraph("解决中文问题了!",font)); */ document.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } /*Document document = new Document(); try { // 建立一个Document对象 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font keyfont = new Font(bfChinese, 11, Font.BOLD);// 设置字体大小 Font textfont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小 document.setPageSize(PageSize.A4);// 设置页面大小 PdfWriter.getInstance(document, new FileOutputStream(outputPath)); document.open(); PdfPTable table = createTable(new float[]{1f, 4f, 2f, 2f, 2.5f, 2.5f, 2f}); table.addCell(createCell("编号", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("文件名", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("广告类型", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("频道包", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("开始日期", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("结束日期", keyfont, Element.ALIGN_CENTER)); table.addCell(createCell("缩略图", keyfont, Element.ALIGN_CENTER)); //设置单元格 document.add(table); document.close(); } catch (Exception e) { e.printStackTrace(); } finally { }*/ } public synchronized static boolean html2Pdf(String outputPath, String xmlStr) { OutputStream os = null; try { //xmlStr = HtmlGenerator.generate("D:/Workspaces/SSMBootstrap/resources/freemaker/template/maintenanceViewTemplate.ftl", new HashMap()); os = new FileOutputStream(outputPath); ITextRenderer renderer = new ITextRenderer(); // DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes("utf-8"))); // renderer.setDocument(doc,null); renderer.setDocumentFromString(xmlStr); // 解决中文支持问题 ITextFontResolver fontResolver = renderer.getFontResolver(); try { fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // 解决图片的相对路径问题 /*String basePath="D:/Tomcat 7.0/webapps/UploadFile"; renderer.getSharedContext().setBaseURL("file:/" + basePath + "/MaintenanceBill"); renderer.getSharedContext().setReplacedElementFactory(new Base64ImgReplacedElementFactory()); renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);*/ renderer.layout(); try { renderer.createPDF(os); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { /*ByteArrayOutputStream baos=new ByteArrayOutputStream(); baos=(ByteArrayOutputStream) os; Hibernate.createBlob(); ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());*/ if (os!=null) { os.flush(); os.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; } /** * * 提供中文 * */ public class ChinaFontProvide implements FontProvider{ @Override public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) { BaseFont bfChinese =null; try { // bfChinese=BaseFont.createFont("STSong-Light", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); bfChinese=BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF,1",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font FontChinese = new Font(bfChinese); return FontChinese; } @Override public boolean isRegistered(String arg0) { return false; } } @RequestMapping("/exportMaintenanceDetailPDF.do") public ModelAndView exportMaintenanceDetailPDF(HttpServletRequest request,Model model){ String htmlStr = request.getParameter("htmlStr"); PDFFileUtil pdfFileUtil= new PDFFileUtil(); String realPath = request.getSession().getServletContext().getRealPath("/"); String pjName = request.getContextPath().substring(1, request.getContextPath().length()); realPath = realPath.replace(pjName,"UploadFile"); String fileName =CommUtil.getUUID()+".pdf"; realPath+="MaintenanceBill\\"+fileName; pdfFileUtil.html2Pdf(realPath, htmlStr); String result="{\"res\":\""+realPath.substring(realPath.indexOf("UploadFile"),realPath.length()).replace("\\", "/")+"\"}"; model.addAttribute("result",result); return new ModelAndView("result"); } /* static{ BaseFont bfChinese_H; try { *//** * 新建一个字体,iText的方法 STSongStd-Light 是字体,在iTextAsian.jar 中以property为后缀 * UniGB-UCS2-H 是编码,在iTextAsian.jar 中以cmap为后缀 H 代表文字版式是 横版, 相应的 V 代表竖版 *//* bfChinese_H = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); headFont = new Font(bfChinese_H, 14, Font.NORMAL); keyFont = new Font(bfChinese_H, 26, Font.BOLD); nbspFont = new Font(bfChinese_H, 13, Font.NORMAL); textfont_H = new Font(bfChinese_H, 10, Font.NORMAL); textfont_B = new Font(bfChinese_H, 12, Font.NORMAL); textfont_13 = new Font(bfChinese_H, 13, Font.NORMAL); textfont_12 = new Font(bfChinese_H, 12, Font.NORMAL); textfont_11 = new Font(bfChinese_H, 11, Font.NORMAL); textfont_10 = new Font(bfChinese_H, 10, Font.NORMAL); textfont_9 = new Font(bfChinese_H, 9, Font.NORMAL); textfont_8 = new Font(bfChinese_H, 8, Font.NORMAL); textfont_7 = new Font(bfChinese_H, 7, Font.NORMAL); textfont_6 = new Font(bfChinese_H, 6, Font.NORMAL); } catch (Exception e) { e.printStackTrace(); } }*/ /** * 设置页面属性 * @param file */ public void setPageProperties(File file) { //自定义纸张 Rectangle rectPageSize = new Rectangle(350, 620); // 定义A4页面大小 //Rectangle rectPageSize = new Rectangle(PageSize.A4); rectPageSize = rectPageSize.rotate();// 加上这句可以实现页面的横置 document = new Document(rectPageSize,10, 150, 10, 40); try { PdfWriter.getInstance(document,new FileOutputStream(file)); document.open(); } catch (Exception e) { e.printStackTrace(); } } /** * 建表格(以列的数量建) * @param colNumber * @return */ public PdfPTable createTable(int colNumber){ PdfPTable table = new PdfPTable(colNumber); try{ //table.setTotalWidth(maxWidth); //table.setLockedWidth(true); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setBorder(1); table.setSpacingBefore(10); table.setWidthPercentage(100); }catch(Exception e){ e.printStackTrace(); } return table; } /** * 建表格(以列的宽度比建) * @param widths * @return */ public PdfPTable createTable(float[] widths){ PdfPTable table = new PdfPTable(widths); try{ //table.setTotalWidth(maxWidth); //table.setLockedWidth(true); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setBorder(1); table.setSpacingBefore(10); table.setWidthPercentage(100); }catch(Exception e){ e.printStackTrace(); } return table; } /** * 表格中单元格 * @param value * @param font * @param align * @return */ public PdfPCell createCell(String value,Font font,int align){ PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(align); cell.setPhrase(new Phrase(value,font)); return cell; } /** * 表格中单元格 * @param value * @param font * @param align * @param colspan * @param rowspan * @return */ public PdfPCell createCell(String value,Font font,int align_v,int align_h,int colspan,int rowspan){ PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(align_v); cell.setHorizontalAlignment(align_h); cell.setColspan(colspan); cell.setRowspan(rowspan); cell.setPhrase(new Phrase(value,font)); return cell; } /** * 创建无边框表格 * @param value * @param font * @param align * @param colspan * @param rowspan * @return */ public PdfPCell createCellNotBorder(String value,Font font,int align_v,int align_h,int colspan,int rowspan){ PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(align_v); cell.setHorizontalAlignment(align_h); cell.setColspan(colspan); cell.setRowspan(rowspan); cell.setPhrase(new Phrase(value,font)); cell.setBorderWidth(0f); return cell; } /** * 建短语 * @param value * @param font * @return */ public Phrase createPhrase(String value,Font font){ Phrase phrase = new Phrase(); phrase.add(value); phrase.setFont(font); return phrase; } /** * 建段落 * @param value * @param font * @param align * @return */ public Paragraph createParagraph(String value,Font font,int align){ Paragraph paragraph = new Paragraph(); paragraph.add(new Phrase(value,font)); paragraph.setAlignment(align); return paragraph; } }