원래, 우리는 Android 측면에서 문서를 생성하고 싶었습니다 (필요합니다 ...). 결국, Android에서 완벽 할 수있는 좋은 방법은 없으며 결국 서버로만 이동할 수 있습니다. 낭비하지 말고 각 프레임 워크가 Android와 그 특성을 지원하지 않는 이유를 기록하십시오. 여전히 Java와 관련된 많은 프레임 워크가 있으며 일부는 나쁘지 않지만 불행히도 그들은 Android를 지원하지 않거나 수수료를 청구하고 가격이 저렴합니다.
개인 테스트 후에는 Java를 지원하지 않는 많은 AWT 패키지를 Android에서 직접 사용할 수 없습니다. 프리 마커는 꽤 좋고 복잡하고 아름다운 문서를 생성 할 수 있지만 불행히도 안드로이드를 지원하지는 않습니다. POI를 사용하여 Android에서 실행될 수 있지만 버전, 형식 등으로 인해 많은 함정을 겪었으며 여전히 WFS와 함께 열릴 수 있습니다. JWORD 및 ASPOSE.WORD를 완벽하게 지원할 수 있으며 JWORD 보호 관찰 기간은 30 일에 불과하며 두 가지 모두 요금이 부과됩니다. ITEXT에는 테스트가 없지만 Android를 지원하지 않는다고합니다.
방법 1 : 프리 마커
이 방법을 사용하려면 DOC 템플릿을 수동으로 작성하고 (그림에 자리 표시 자 사용을 기억하십시오) XML 파일로 저장해야합니다. 특정 태그 $ {}의 컨텐츠를 동적으로 교체하여 생성하십시오. 예:
먼저, 렌더링을 가져 가자 :
공개 클래스 docutil {public configuration configuration = null; public docutil () {configure = 새 구성 (configuration.version_2_3_22); configure.setDefaultEncoding ( "UTF-8"); } /*** doc 템플릿을 기반으로 Word 파일 생성* @param datamap 템플릿에 채워야하는 데이터* @param downloadtype 파일 이름* @param savepate save path* /public void createoc (map <string, object> datamap, string downloadtype, String savepate) {try {// 템플릿을로드 해야하는 템플릿을로드합니다. // 템플릿 장치 메소드와 경로를 설정하면 프리 마커는 여러 템플릿로드 메소드를 지원합니다. 서블릿, 클래스 경로 및 데이터베이스 마운트를 다시로드 할 수 있습니다. // 템플릿 파일을로드하고 testDoc configure.setClassFortemPlatEloading (this.getClass (), "/testDoc")에 배치합니다. // 객체 래퍼를 설정 // configure.setObjectWrapper (새 defaultObjectWrapper ()); // 예외 핸들러 set handler configure.setTemplateExceptionAndler (TemplateExceptionHandler.ignore_handler); // 템플릿 객체를 정의하고 템플릿 유형 이름은 downloadType 템플릿 = configure.getTemplate (downloadtype+". xml")와 일치해야합니다. 파일 Outfile = 새 파일 (SavePath); 작가 out = null; out = new BufferedWriter (New OutputStreamWriter (New FileOutputStream (Outfile), "UTF-8"); template.process (datamap, out); out.close (); } catch (ioexception e) {e.printstacktrace (); } catch (TemplateException e) {e.printstacktrace (); }} public String getImagest (String imgfile) {inputStream in = null; 바이트 [] data = null; try {in = new FileInputStream (imgfile); data = new Byte [in.available ()]; in.Read (데이터); 넣다(); } catch (filenotfoundException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); } base64encoder encoder = 새로운 base64encoder (); return encoder.encode (데이터); }} public class testdoc {public static void main (String [] args) {docutil docutil = new docutil (); map <string, object> datamap = new Hashmap <string, object> (); datamap.put ( "이름", "joanna"); Datamap.put ( "Examnum", "11111111111111"); datamap.put ( "idcard", "222222222222222222222222222222222222222222222222222222222222222222222 2222222222222222222222222222222222222222222222222222222222222222; DataMap.put ( "CARMODEL", "DRIVINGSHOOL", "BusyType", "DataMap.put"); docutil.getimagest ( "d : //img//userimg1.png"); DataMap.put ( "FirstExamscores", "0 점, 실패"); Datamap.put ( "FirstPic2", docutil.getimagest ( "d : //img//firstpic2.png"); "12 : 46 : 50-13 : 05 : 37"); Datamap.put ( "SecondExamScores", "90 포인트, 패스"); datamap.put ( "SecondDeductime", ""); datamap.put ( "secondpic1", docutil.getimagest ( "d : //img//secondpic1.png")); datamap.put ( "sec Datamap.put ( "SecondPic3", docutil.getimagest ( "d : //img//secondpic3.png"); docutil.createdoc (datamap, "basedoc", "d : //yanqiong.doc"); }} XML 파일이 너무 길어 게시하지 않겠습니다 ...
마지막으로, Android를 사용할 수없는 이유 : http://stackoverflow.com/questions/25929542/use-freemarker-library-in-endroid
목록 및 라인 브레이크의 동적 표시에 대한 추가 질문
요구 사항은 분명합니다. 위의 공제 항목에서 여러 공제 품목이 있으면 각 라인이 나뉘어지기를 원합니다.
표시 할 컨텐츠에 최신 라인을 직접 추가하면 효과가 없으며 Newline으로 기능하지 않습니다.
<#list> </list>와 같은 FTL 태그를 추가하면 XML에서 인식되지 않은 일부 문제가 발생하여 프로젝트가 실행되지 않습니다.
해결하다:
여러 공제 품목을 표시 해야하는 위치에 라인 브레이크를 추가하고 추가하십시오.
<#list firstDedUctem as FirstItem>
<w : t> $ {firstItem} </w : t> <w : br/>
</#목록>
변경 :
List <string> strs = new ArrayList <string> ();
strs.add ( "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111음까지들들은들들들들들 보지들 보인다.
strs.add ( "222222222222222222222222);
strs.add ( "3333333333333");
Datamap.put ( "FirstDductItem", strs);
docutil.java로 변경하십시오.
// 템플릿 객체를 정의하고 템플릿 유형 이름은 다운로드 유형과 일치해야합니다.
템플릿 = configure.getTemplate (downloadType+". ftl"); 현재 XML 파일은 오류를보고 할 것이며, 물론 프로젝트를 컴파일하고 실행하는 것은 불가능합니다. 저장하려면 .xml 파일을 .ftl 파일로 변경해야합니다. 그런 다음 컴파일 및 실행, 렌더링 :
방법 2 : POI
이 방법을 사용하여 많은 버전 문제가 발생했습니다. 이것은 POI3.7+Word2007을 기반으로하며 테스트는 완벽하게 실행될 수 있습니다.
Word2007을 사용하여 문서 템플릿을 수동으로 생성해야합니다 (다른 세대를 사용하면 오류가 발생합니다. 파일을 열 수 없습니다). 위와 유사하게 $ {}로 동적으로 업데이트 해야하는 컨텐츠를 교체하지만 XML 문서 형식으로 저장할 필요는 없습니다.
/** * xwpfdocument를 사용자 정의하고 createPicture () 메소드 * @author joanna.yan * */public class customxwpfdocument 확장 xwpfdocument {public customxwpfdocument (inputstream in)는 ioexception {super (in); } public customxwpfdocument () {super (); } public customxwpfdocument (opcpackage pkg)는 ioexception {super (pkg); } public void createPicture (int id, int width, int height, xwpfparagraph 단락) {최종 int emu = 9525; 너비 *= EMU; 높이 *= EMU; String blipid = ((poixmlDocumentPart) getAllPictures (). get (id)). getPackAgerElationship (). getId (); ctinline inline = paragraph.createrun (). getCtr (). addnewdrawing (). addnewinline (); 문자열 picxml = "" + "<a : 그래픽 xmlns : a =/"http://schemas.openxmlformats.org/drawingml/2006/main/ ">" + "<a : GraphicData uri =/"http://schemas.openxmlformats.org/ " +" + " +" + " +" + " +" <pic : pic xmlns : pic =/"http://schemas.openxmlformats.org/drawingml/2006/picture/"> ">" + "<pic : nvpicpr>" + "<pic : cnvpr id =/" " + id +"/"name =/"genated/" +"<cnvcpr/" +"< </pic : nvpicpr> " +"<<pic : blipfill> " +"<a : blip r : embed =/"" + blipid + "/"xmlns : r =/"http://schemas.openxmlformats.org/officedocument/2006/relationships/" + "<a : : <a : : <a : <a : : </a : 스트레치> " +"</pic : blipfill> " +"<pic : sppr> " +"<a : xfrm> " +"<a : off x =/"0/"y =/"0/"/> " +"<a : ext cx =/"" + width + "/"cy =/"" + height + "/>"</</a : xfrm> ": prstge. prst =/"rect/"> " +"<a : avlst/> " +"</a : prstgeom> " +"</pic : sppr> " +"</pic : pic> " +"</a : GraphicData> " +"</a : 그래픽> "; inline.addnewgraphic (). addnewgraphicdata (); xmltoken xmltoken = null; try {xmltoken = xmltoken.factory.parse (picxml); } catch (xmlexection e) {e.printstacktrace (); } inline.set (xmltoken); inline.setDistt (0); inline.setdistb (0); inline.setDistl (0); inline.setdist (0); ctpositives2d extent = inline.addnewextent (); extent.setcx (너비); extent.setcy (높이); ctnonvisualdrawingprops docpr = inline.addnewdocpr (); docpr.setid (id); docpr.setName ( "image"+id); docpr.setdescr ( "테스트"); }} /** * 단어 2007 * poi 버전 3.7 * @author joanna.yan */public class wordUtil {public static customxwpfdocument generateword (map <string, object> param, string 템플릿) {customxwpfdocumument doc = null; {opcpackage pack = poixmldocument.openpackage (템플릿); doc = 새로운 customxwpfdocument (pack); if (param! = null & ¶m.size ()> 0) {// 단락 목록을 처리 <xwpfparagraph> paragraphlist = doc.getParagraphs (); ProcessAgraphaphs (단락리스트, Param, Doc); // TABLE ITERATOR <xwpftable> it = doc.getTablesTerator (); while (it.hasnext ()) {xwpftable table = it.next (); List <xwpftberow> rows = table.getrows (); for (xwpftablerow row : rows) {list <xwpftablecell> cells = row.gettablecells (); for (xwpftablecell cell : cells) {list <xwpfparagraph> paragraphlisttable = cell.getparagraphs (); ProcessAgraphaphs (단락, param, doc); }}}}}} catch (ioexception e) {e.printstacktrace (); } reto doc; } / ** * 프로세스 단락 * @param paragraphlist * @param param * @param doc * / public static void processAgraphs (list <xwpfparagraph> paragraphlist, map <string, 객체> param, customxwpfdocument doc) {if (paragraphlist! = null & ¶graphlist.size ()> 0) {) : paragraphlist) {list <xwpfrun> run = paragraph.getRuns (); for (xwpfrun run : run) {문자열 text = run.getText (0); if (text! = null) {boolean issettext = false; for (Entry <string, object> entry : param.entryset ()) {String key = entry.getKey (); if (text.indexof (key)! = -1) {issettext = true; 객체 값 = Entry.GetValue (); if (value instancef string) {// 텍스트 대체 텍스트 = text.replace (key, value.toString ()); } else if (value instanceof map) {// 그림 교체 텍스트 = text.replace (key, ""); 맵 pic = (맵) 값; int width = integer.parseint (pic.get ( "width"). toString ()); int height = integer.parseint (pic.get ( "height"). toString ()); int pictype = getPictureType (pic.get ( "type"). toString ()); 바이트 [] bytearray = (byte []) pic.get ( "content"); BytearRayInputStream ByteInputStream = New BytearRayInputStream (ByteArray); try {int ind = doc.addpicture (byteinputstream, pictype); Doc.CreatePicture (ind, 너비, 높이, 단락); } catch (invalidformatexception e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); }}}}}} if (issettext) {run.settext (text, 0); }}}}}}}}} / ** * 이미지 유형에 따라 해당 이미지 유형 코드를 가져옵니다. if (pictype! = null) {if (pictype.equalsignorecase ( "png")) {res = customxwpfdocument.picture_type_png; } else if (pictype.equalsignorecase ( "dib")) {res = customxwpfdocument.picture_type_dib; } else if (pictype.equalsignorecase ( "emf")) {res = customxwpfdocument.picture_type_emf; } else if (pictype.equalsignorecase ( "jpg") || pictype.equalsignorecase ( "jpeg")) {res = customxwpfdocument.picture_type_jpeg; } else if (pictype.equalsignorecase ( "wmf")) {res = customxwpfdocument.picture_type_wmf; }} return res; }} public class testpoi {public static void main (String [] args)은 ioexception {map <string, object> param = new Hashmap <String, Object> (); param.put ( "$ {name}", "joanna.yan"); param.put ( "$ {examnum}", "00000000000001"); param.put ( "$ {idcard}", "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111까지까지까지 ').들은 param.put ( "$ {carmodel}", "C1"); customxwpfdocument doc = wordutil.generateword (param, "d : //joanna.docx"); fileoutputStream fopts = new FileOutputStream ( "d : //yan.docx"); Doc.Write (fopts); fopts.close (); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.