It was supposed to generate doc on the Android side (this requirement ...). Finally, there's no good way to do it perfectly on Android, and finally move on to the server. Do not waste, or record the reasons why the frameworks do not support Android and their characteristics. Java-related frameworks are still a lot of, a few are good, but either do not support Android, or to charge the price is not low.
After hands-on testing, Android does not support Java's AWT Many packages cannot be used directly on Android, Freemarker is pretty good, can produce complex beautiful doc, unfortunately does not support Android. With POI on Android can run, but all the way because of the version, format, and so go a lot of pits, with WFS open or garbled. Jword, Aspose.word can support the perfect, Jword probation period only 30 days both charges are not expensive. Itext did not test, but heard that it does not support Android.
method One:freemarker
This method requires you to manually create a doc template (the picture remembers to use a placeholder) and save it as an XML file. Generated by dynamically replacing content in a specific label ${}. Example
First up Effect chart:
public class Docutil {public Configuration configure=null;
Public Docutil () {configure=new Configuration (configuration.version_2_3_22);
Configure.setdefaultencoding ("Utf-8"); /** * Generate Word file based on doc template * @param datamap need to fill in the template data * @param downloadtype file name * @param savepath save path/Public void Createdoc (map<string,object> datamap,string downloadtype,string savepath) {try {//Load templates that need to be loaded Template
Template=null; Sets the template appliance method and path, Freemarker supports a variety of template loading methods.
Can be Servlet,classpath, database mount.
Load template file, placed under Testdoc configure.setclassfortemplateloading (This.getclass (), "/testdoc");
Set Object wrapper//Configure.setobjectwrapper (New Defaultobjectwrapper ());
Set exception handler Configure.settemplateexceptionhandler (Templateexceptionhandler.ignore_handler);
Define the template object, note that the template type name is consistent with the Downloadtype template=configure.gettemplate (downloadtype+ ". xml");
File Outfile=new file (Savepath);
Writer 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 Getimagestr (string imgfile) {InputStream in=null;
Byte[] Data=null;
try {in=new fileinputstream (imgfile);
Data=new byte[in.available ()];
In.read (data);
In.close ();
catch (FileNotFoundException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
} base64encoder encoder=new Base64encoder ();
return Encoder.encode (data);
}
}
public class Testdoc {public static void main (string[] args) {docutil docutil=new docutil ();
Map<string, object> datamap=new hashmap<string, object> ();
Datamap.put ("name", "Joanna");
Datamap.put ("Examnum", "111111111111");
Datamap.put ("Idcard", "222222222222222222");
Datamap.put ("Carmodel", "C1");
Datamap.put ("Drivingschool", "Test Driving School");
Datamap.put ("Busytype", "initial claim");
Datamap.put ("Examdate", "2016-03-10");
Datamap.put ("OrderCount", "1th Time");
Datamap.put ("UserImg1", Docutil.getimagestr ("D:\\img\\userimg1.png"));
Datamap.put ("UserImg2", Docutil.getimagestr ("D:\\img\\userimg2.png"));
Datamap.put ("Firstexamtime", "12:41:17-12:44:38");
Datamap.put ("Firstexamscores", "0 points, failed");
Datamap.put ("Firstdeductitem", "12:44:15 20102, 1th reverse warehousing, body line deduction 100 points");
Datamap.put ("FirstPic1", Docutil.getimagestr ("D:\\img\\firstpic1.png"));
Datamap.put ("FirstPic2", Docutil.getimagestr ("D:\\img\\firstpic2.png")); Datamap.put ("FirstPic3", Docutil.getimagestr ("d:\\img\\fIrstpic3.png "));
Datamap.put ("Secondexamtime", "12:46:50-13:05:37");
Datamap.put ("Secondexamscores", "90 points, passed");
Datamap.put ("Seconddeductitem", "");
Datamap.put ("SecondPic1", Docutil.getimagestr ("D:\\img\\secondpic1.png"));
Datamap.put ("SecondPic2", Docutil.getimagestr ("D:\\img\\secondpic2.png"));
Datamap.put ("SecondPic3", Docutil.getimagestr ("D:\\img\\secondpic3.png"));
Docutil.createdoc (Datamap, "BaseDoc", "D:\\yanqiong.doc");
}
}
The XML file is too long to be pasted ...
Finally attach the reason why Android is not available: http://stackoverflow.com/questions/25929542/use-freemarker-library-in-android
additional questions about dynamic display list and line wrapping
The requirement is clear: in the above deduction, if I have a few deduction items, I want to show a line break each.
Directly in the content to be displayed with line breaks, and no effect, can not play the role of wrapping.
When you add FTL tags, such as < #list ></list>, there are some problems that are not recognized in XML, causing the project to not run.
Solve:
Add and add line breaks where you want to display multiple deduction points:
< #list Firstdeductitem as firstitem>
<w:t>${firstItem}</w:t><w:br/>
</#list >
In Testdoc.java, read:
List<string> strs=new arraylist<string> ();
Strs.add ("1111111111111111111");
Strs.add ("222222222222222");
Strs.add ("333333333333333");
Datamap.put ("Firstdeductitem", STRs);
In Docutil.java, read:
Define template objects, note that template type names are consistent with Downloadtype
Template=configure.gettemplate (downloadtype+ ". FTL"); The XML file will not be able to compile the running project, and you will need to change the. xml file to the. ftl file save. Re-compile run, Effect diagram:
Method Two: Poi
There are many version problems with this method, which is based on poi3.7+word2007 and the test works perfectly.
You need to manually generate the document template with Word2007 (error with other builds: Unable to open the file) and replace the content that needs to be dynamically updated with ${}, similar to the above, but do not need to be saved as an XML document format.
/** * Custom xwpfdocument and rewrite Createpicture () method * @author Joanna.yan * */public class Customxwpfdocument extends
ment{Public customxwpfdocument (InputStream in) throws ioexception{super (in);
Public Customxwpfdocument () {super ();
Public customxwpfdocument (Opcpackage pkg) throws ioexception{super (pkg);
} public void createpicture (int id,int Width,int height,xwpfparagraph paragraph) {final int emu=9525;
Width *=emu;
Height *=emu;
String blipid= ((Poixmldocumentpart) getallpictures (). Get (ID)). getpackagerelationship (). GetId ();
Ctinline Inline=paragraph.createrun (). GETCTR (). addnewdrawing (). Addnewinline (); String picxml= "" + "<a:graphic xmlns:a=\" http://schemas.openxmlformats.org/drawingml/2006/main\ ">" + " ; A:graphicdata uri=\ "http://schemas.openxmlformats.org/drawingml/2006/picture\" > "+" <pic:pic xmlns:pic=\ "HT Tp://schemas.openxmlformats.org/drawingml/2006/picture\ ">" + "<pic:nvPicPr>" + "<PIC:CNVPR id=\ "" + ID + "\" name=\ "generated\"/> "+" <pic:cNvPicPr/> "+" </pic:nvPicPr> "+" <pic:blipFill> "+" <a:blip r:embed=\ "" + blipid + "\ xmlns:r=\" Http://schemas.ope
Nxmlformats.org/officedocument/2006/relationships\ "/>" + "<a:stretch>" + "<a:fillRect/>"
+ "</a:stretch>" + "</pic:blipFill>" + "<pic:spPr>" + "<a:xfrm>" + "<a:off x=\" 0\ "y=\" 0\ "/>" + "<a:ext cx=\" "+ width +" \ "cy=\" "+ Height + "\"/> "+" </a:xfrm> "+" <a:prstgeom prst=\ "rect\" > "+" <a:avLst/> "+" </a:prstGeom> "+" </pic:spPr> "+" </pic:pic> "+" </a:graphicData> "+" <
/a:graphic> ";
Inline.addnewgraphic (). Addnewgraphicdata ();
Xmltoken Xmltoken=null;
try {xmltoken=xmltoken.factory.parse (picxml); }catch (XmlException e) {e.printstacktrace ();
} inline.set (Xmltoken);
INLINE.SETDISTT (0);
INLINE.SETDISTB (0);
Inline.setdistl (0);
INLINE.SETDISTR (0);
Ctpositivesize2d extent=inline.addnewextent ();
EXTENT.SETCX (width);
Extent.setcy (height);
Ctnonvisualdrawingprops DOCPR=INLINE.ADDNEWDOCPR ();
Docpr.setid (ID);
Docpr.setname ("picture" +id);
DOCPR.SETDESCR ("test");
}
}
/** * Applies to Word 2007 * POI version 3.7 * @author Joanna.yan */public class Wordutil {public static customxwpfdocument
Generateword (map<string, object> param,string template) {customxwpfdocument doc=null;
try {opcpackage pack=poixmldocument.openpackage (template);
Doc=new customxwpfdocument (Pack);
if (Param!=null&¶m.size () >0) {//process paragraph list<xwpfparagraph> paragraphlist = Doc.getparagraphs ();
Processparagraphs (paragraphlist, Param, doc);
Process table Iterator<xwpftable> it = Doc.gettablesiterator ();
while (It.hasnext ()) {xwpftable table = It.next ();
list<xwpftablerow> rows = Table.getrows ();
for (Xwpftablerow row:rows) {list<xwpftablecell> cells = row.gettablecells ();
for (Xwpftablecell cell:cells) {list<xwpfparagraph> paragraphlisttable = cell.getparagraphs ();
Processparagraphs (paragraphlisttable, Param, doc); catch (IOEXception e) {e.printstacktrace ();
return doc; /** * Processing Paragraph * @param paragraphlist * @param param * @param doc/public static void Processparagraphs (List <XWPFParagraph> paragraphlist,map<string, object> param,customxwpfdocument doc) {if (paragraphlist!=null &¶graphlist.size () >0) {for (xwpfparagraph paragraph:paragraphlist) {list<xwpfrun> Runs=para
Graph.getruns ();
for (Xwpfrun run:runs) {String 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;
Object Value=entry.getvalue ();
if (value instanceof String) {//Text replaces Text=text.replace (key, value.tostring ());
}else if (value instanceof Map) {//Picture replacement Text=text.replace (Key, "");
Map pic= (map) value; int Width=integer.parseint (pic.get("width"). toString ());
int Height=integer.parseint (pic.get ("height"). toString ());
int Pictype=getpicturetype (Pic.get ("type"). toString ());
Byte[] ByteArray = (byte[]) pic.get ("content");
Bytearrayinputstream Byteinputstream = new Bytearrayinputstream (ByteArray);
try {int ind = doc.addpicture (Byteinputstream,pictype);
Doc.createpicture (Ind, width, height,paragraph);
catch (Invalidformatexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
}} if (Issettext) {run.settext (text, 0); /** * to get the corresponding picture type code based on the picture type * @param pictype * @return/public static int Getpicturet
Ype (String pictype) {int res = customxwpfdocument.picture_type_pict;
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) throws IOException {
map<string, object> param =new hashmap<string, object> ();
Param.put ("${name}", "Joanna.yan");
Param.put ("${examnum}", "000000000001");
Param.put ("${idcard}", "111111111111111111");
Param.put ("${carmodel}", "C1");
Customxwpfdocument Doc=wordutil.generateword (param, "d:\\joanna.docx");
FileOutputStream fopts = new FileOutputStream ("D:\\yan.docx");
Doc.write (fopts);
Fopts.close ();
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.