我在尝试生成文档时遇到问题。
目标:根据Android中的.docx模板生成文档
我的项目: https://i.stack.imgur.com/5NEm1.jpg
我在插件中使用它:xdocreport-1.0.4.jar
我的模板 Test.docx:
https://i.stack.imgur.com/firvA.jpg - 输入:MergeField
我的问题:
代码:GeneradorDocumentosService.java https://github.com/DomingoMG/TemplateDocxAndroid/blob/master/Main.java
public static InputStream loadDocumentAsStream(String filePath) throws IOException
{
URL url = new File(filePath).toURI().toURL();
InputStream documentAsStream = url.openStream();
return documentAsStream;
}
代码:Main.java :https://github.com/DomingoMG/TemplateDocxAndroid/blob/master/Main.java
public static void generateDocument(String rutaPlantilla, String extension, boolean convertirPdf)
throws IOException, XDocReportException
{
Map<String, Object> variablesMap = new HashMap<String, Object>();
variablesMap.put("name", name);
variablesMap.put("surname", surname);
variablesMap.put("date", date);
// 2) Create fields metadata to manage lazy loop (#forech velocity)
// for table row.
FieldsMetadata metadata = new FieldsMetadata();
metadata.addFieldAsList("listaNumeros.Numero");
metadata.addFieldAsList("listaNumeros.Cuadrado");
metadata.addFieldAsList("listaNumeros.Raiz");
// Mapa con las variables de tipo imagen. Estas variables contienen el path de la imagen
Map<String, String> imagenesMap = new HashMap<String, String>();
imagenesMap.put("header_image_logo", "./Logo.png");
GeneradorDocumentosService generadorDocumentosService = new GeneradorDocumentosService();
byte[] mergedOutput = generadorDocumentosService.generarDocumento(rutaPlantilla,
TemplateEngineKind.Freemarker, variablesMap, imagenesMap, convertirPdf
, metadata
);
FileOutputStream os = new FileOutputStream("Faycan_Contract_"+"." +extension);
os.write(mergedOutput);
os.flush();
os.close();
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNombre = (EditText) findViewById(R.id.txtNombre);
txtApellidos = (EditText) findViewById(R.id.txtApellidos);
txtFecha = (EditText) findViewById(R.id.txtFecha);
name = txtNombre.getText().toString();
surname = txtApellidos.getText().toString();
date = txtFecha.getText().toString();
btnGenerar = (Button) findViewById(R.id.btnGenerar);
btnGenerar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
generateDocument("file:///android_asset/test.docx", "docx", false);
}catch (Exception e)
{
Toast.makeText(getApplicationContext(), "The document could not be generated"+e,
Toast.LENGTH_SHORT).show();
}
}
});
}