在我的Android应用程序中,我想创建一个带有Image文件的word文档。为此,我已下载docx4j.jar并复制到libs文件夹中。当我尝试从路径中获取图像(也是ImageView中的位图)并保存在文档中时,应用程序会因我在下面附加的错误而崩溃
下面给出了我试过的代码片段,
import java.io.ByteArrayOutputStream;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;
public class SaveWordDocument {
public SaveWordDocument(View v) {
// TODO Auto-generated constructor stub
try {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.createPackage();
Bitmap bmp = loadBitmapFromView(v);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
try {
addImageToPackage(wordMLPackage, bytes);
wordMLPackage.save(new java.io.File(
"/sdcard0/OrderPlace/Order.docx"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void addImageToPackage(
WordprocessingMLPackage wordMLPackage, byte[] bytes)
{
BinaryPartAbstractImage imagePart;
try {
imagePart = BinaryPartAbstractImage
.createImagePart(wordMLPackage, bytes);
int docPrId = 1;
int cNvPrId = 2;
Inline inline = imagePart.createImageInline("Filename hint",
"Alternative text", docPrId, cNvPrId, false);
P paragraph = addInlineImageToParagraph(inline);
wordMLPackage.getMainDocumentPart().addObject(paragraph);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static P addInlineImageToParagraph(Inline inline) {
// Now add the in-line image to a paragraph
ObjectFactory factory = new ObjectFactory();
P paragraph = factory.createP();
R run = factory.createR();
paragraph.getContent().add(run);
Drawing drawing = factory.createDrawing();
run.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
return paragraph;
}
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width,
v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
}
当我调试代码时,错误将抛出以下行,
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.createPackage();
即使我试了好几个小时后也找不到解决方案。请帮我找到解决方案。