注:我使用的word 2016
功能簡介:
(1)使用jsoup解析html獲得我用來生成word的文本(這個大家能夠忽略)
(2)生成word、設置頁邊距、設置頁腳(頁碼),設置頁碼(文本)html
1、解析htmlmaven
Document doc = Jsoup.parseBodyFragment(contents); Element body = doc.body(); Elements es = body.getAllElements();
2、循環Elements獲取我須要的html標籤ide
boolean tag = false; for (Element e : es) { //跳過第一個(默認會把整個對象當作第一個) if(!tag) { tag = true; continue; } //建立段落:生成word(核心) createXWPFParagraph(docxDocument,e); }
3、生成段落字體
/** * 構建段落 * @param docxDocument * @param e */ public static void createXWPFParagraph(XWPFDocument docxDocument, Element e){ XWPFParagraph paragraph = docxDocument.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(e.text()); run.setTextPosition(35);//設置行間距 if(e.tagName().equals("titlename")){ paragraph.setAlignment(ParagraphAlignment.CENTER);//對齊方式 run.setBold(true);//加粗 run.setColor("000000");//設置顏色--十六進制 run.setFontFamily("宋體");//字體 run.setFontSize(24);//字體大小 }else if(e.tagName().equals("h1")){ addCustomHeadingStyle(docxDocument, "標題 1", 1); paragraph.setStyle("標題 1"); run.setBold(true); run.setColor("000000"); run.setFontFamily("宋體"); run.setFontSize(20); }else if(e.tagName().equals("h2")){ addCustomHeadingStyle(docxDocument, "標題 2", 2); paragraph.setStyle("標題 2"); run.setBold(true); run.setColor("000000"); run.setFontFamily("宋體"); run.setFontSize(18); }else if(e.tagName().equals("h3")){ addCustomHeadingStyle(docxDocument, "標題 3", 3); paragraph.setStyle("標題 3"); run.setBold(true); run.setColor("000000"); run.setFontFamily("宋體"); run.setFontSize(16); }else if(e.tagName().equals("p")){ //內容 paragraph.setAlignment(ParagraphAlignment.BOTH);//對齊方式 paragraph.setIndentationFirstLine(WordUtil.ONE_UNIT);//首行縮進:567==1釐米 run.setBold(false); run.setColor("001A35"); run.setFontFamily("宋體"); run.setFontSize(14); //run.addCarriageReturn();//回車鍵 }else if(e.tagName().equals("break")){ paragraph.setPageBreak(true);//段前分頁(ctrl+enter) } }
4、設置頁邊距orm
/** * 設置頁邊距 (word中1釐米約等於567) * @param document * @param left * @param top * @param right * @param bottom */ public static void setDocumentMargin(XWPFDocument document, String left,String top, String right, String bottom) { CTSectPr sectPr = document.getDocument().getBody().addNewSectPr(); CTPageMar ctpagemar = sectPr.addNewPgMar(); if (StringUtils.isNotBlank(left)) { ctpagemar.setLeft(new BigInteger(left)); } if (StringUtils.isNotBlank(top)) { ctpagemar.setTop(new BigInteger(top)); } if (StringUtils.isNotBlank(right)) { ctpagemar.setRight(new BigInteger(right)); } if (StringUtils.isNotBlank(bottom)) { ctpagemar.setBottom(new BigInteger(bottom)); } }
5、建立頁眉htm
/** * 建立默認頁眉 * * @param docx XWPFDocument文檔對象 * @param text 頁眉文本 * @return 返回文檔幫助類對象,可用於方法鏈調用 * @throws XmlException XML異常 * @throws IOException IO異常 * @throws InvalidFormatException 非法格式異常 * @throws FileNotFoundException 找不到文件異常 */ public static void createDefaultHeader(final XWPFDocument docx, final String text){ CTP ctp = CTP.Factory.newInstance(); XWPFParagraph paragraph = new XWPFParagraph(ctp, docx); ctp.addNewR().addNewT().setStringValue(text); ctp.addNewR().addNewT().setSpace(SpaceAttribute.Space.PRESERVE); CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr); XWPFHeader header = policy.createHeader(STHdrFtr.DEFAULT, new XWPFParagraph[] { paragraph }); header.setXWPFDocument(docx); }}
6、建立頁腳對象
/** * 建立默認的頁腳(該頁腳主要只居中顯示頁碼) * * @param docx * XWPFDocument文檔對象 * @return 返回文檔幫助類對象,可用於方法鏈調用 * @throws XmlException * XML異常 * @throws IOException * IO異常 */ public static void createDefaultFooter(final XWPFDocument docx) { // TODO 設置頁碼起始值 CTP pageNo = CTP.Factory.newInstance(); XWPFParagraph footer = new XWPFParagraph(pageNo, docx); CTPPr begin = pageNo.addNewPPr(); begin.addNewPStyle().setVal(STYLE_FOOTER); begin.addNewJc().setVal(STJc.CENTER); pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.BEGIN); pageNo.addNewR().addNewInstrText().setStringValue("PAGE \\* MERGEFORMAT"); pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE); CTR end = pageNo.addNewR(); CTRPr endRPr = end.addNewRPr(); endRPr.addNewNoProof(); endRPr.addNewLang().setVal(LANG_ZH_CN); end.addNewFldChar().setFldCharType(STFldCharType.END); CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr); policy.createFooter(STHdrFtr.DEFAULT, new XWPFParagraph[] { footer }); }
7、自定義標題樣式(這個在我另外一篇word基礎中也有說起)blog
/** * 增長自定義標題樣式。這裏用的是stackoverflow的源碼 * * @param docxDocument 目標文檔 * @param strStyleId 樣式名稱 * @param headingLevel 樣式級別 */ private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) { CTStyle ctStyle = CTStyle.Factory.newInstance(); ctStyle.setStyleId(strStyleId); CTString styleName = CTString.Factory.newInstance(); styleName.setVal(strStyleId); ctStyle.setName(styleName); CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance(); indentNumber.setVal(BigInteger.valueOf(headingLevel)); // lower number > style is more prominent in the formats bar ctStyle.setUiPriority(indentNumber); CTOnOff onoffnull = CTOnOff.Factory.newInstance(); ctStyle.setUnhideWhenUsed(onoffnull); // style shows up in the formats bar ctStyle.setQFormat(onoffnull); // style defines a heading of the given level CTPPr ppr = CTPPr.Factory.newInstance(); ppr.setOutlineLvl(indentNumber); ctStyle.setPPr(ppr); XWPFStyle style = new XWPFStyle(ctStyle); // is a null op if already defined XWPFStyles styles = docxDocument.createStyles(); style.setType(STStyleType.PARAGRAPH); styles.addStyle(style); }
8、設置頁碼大小及紙張方向ci
/** * 設置頁面大小及紙張方向 landscape橫向 * @param document * @param width * @param height * @param stValue */ public void setDocumentSize(XWPFDocument document, String width,String height, STPageOrientation.Enum stValue) { CTSectPr sectPr = document.getDocument().getBody().addNewSectPr(); CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz(); pgsz.setH(new BigInteger(height)); pgsz.setW(new BigInteger(width)); pgsz.setOrient(stValue); }
9、效果展現文檔
10、demo源碼及生成的word文件(相應的jar包你們能夠去阿里的maven倉庫下載)
demo:https://pan.baidu.com/s/1jHFLniI