Android使用poi生成docx文件,插入图片

//创建图片(直接写一个类继承XWPFDocument,增加如下方法)
public void createPicture(int id, int width, int height, XWPFParagraph paragraph) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        String blipId = 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=\"http://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.openxmlformats.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 xe) {
            xe.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("图片" + id);
        docPr.setDescr("测试");
    }

模板图片

                                                     


 //根据两个模板创建新的文件
private void writeNewDoc() {
        try {
            InputStream in_w = getAssets().open("template_w.docx");
            MyXWPFDocument newDoc = new MyXWPFDocument(in_w);
            List<XWPFParagraph> newParas = newDoc.getParagraphs();
            int startPoint = -1;
            for (int i = 0; i < newParas.size(); i++) {
                XWPFParagraph para = newParas.get(i);
                List<XWPFRun> runs = para.getRuns();
                for (int j = 0; j < runs.size(); j++) {
                    if ("title".equals(runs.get(j).text())) {
                        para.removeRun(j);
                        para.createRun().setText("错题大全", 0);
                        startPoint = i;
                        break;
                    }
                }
                if (startPoint != -1) {
                    break;
                }
            }

            InputStream in = getAssets().open("template.docx");
            XWPFDocument doc = new XWPFDocument(in);
            List<XWPFParagraph> paras = doc.getParagraphs();
            System.out.println(startPoint);
            if (startPoint != -1) {
                XWPFParagraph insertNewParagraph = newParas.get(startPoint + 1);
                XmlCursor xmlCursor = insertNewParagraph.getCTP().newCursor();
                for (int j = 0; j < 3; j++) {
                    for (int i = 0; i < paras.size(); i++) {
                        System.out.println("i=" + i);
                        XWPFParagraph para = paras.get(i);//获得传过来的段落对象
                        CTPPr oldPPr = para.getCTP().getPPr();//获取段落对象的样式的ppr标签
                        insertNewParagraph.getCTP().setPPr(oldPPr);

                        List<XWPFRun> runs = para.getRuns();//获取run对象
                        for (int k = 0; k < runs.size(); k++) {
                            XWPFRun oldRun = runs.get(k);
                            System.out.println(oldRun.text());
                            CTRPr oldRPr = oldRun.getCTR().getRPr();
                            CTRPrChange oldRPrChange = oldRPr.getRPrChange();//run标签里也有rprchange标签也需要像上面一样设置

                            if (oldRPrChange != null) {
                                oldRPr.unsetRPrChange();
                            }

                            XWPFRun newRun = insertNewParagraph.createRun();
                            newRun.getCTR().setRPr(oldRPr);
                            String text = oldRun.text();
                            if ("stitle".equals(text)) {
                                text = "错题" + j;
                            } else if ("mtitle".equals(text)) {
                                text = "备注";
                            } else if ("img".equals(text)) {
                                text = "";
                                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), j % 2 == 0 ? R.drawable.mcl : R.drawable.berd);
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                                try {
                                    newDoc.addPictureData(byteInputStream, MyXWPFDocument.PICTURE_TYPE_JPEG);
                                    newDoc.createPicture(newDoc.getAllPictures().size() - 1, 150, 150, insertNewParagraph);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                byteInputStream.close();
                                byteArrayOutputStream.close();
                                bitmap.recycle();
                            }
                            newRun.setText(text);
                            insertNewParagraph.addRun(newRun);
                        }
                        xmlCursor.toNextSibling();//下移光标
                        insertNewParagraph = newDoc.insertNewParagraph(xmlCursor);//在当前光标处插入新的段落
                        xmlCursor = insertNewParagraph.getCTP().newCursor();
                    }
                }
            }

            File saveFile = new File(savePath + "write/save.docx");
            if (saveFile.exists()) {
                saveFile.delete();
            }
            saveFile.getParentFile().mkdirs();
            saveFile.createNewFile();

            FileOutputStream os = new FileOutputStream(saveFile);
            //把doc输出到输出流
            newDoc.write(os);
            os.close();
            in.close();
            System.out.println("finish writeDocx.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
使用POIdocx转换为html,需要注意以下几点: 1. 需要将docx中的图片单独提取出来,并将其插入到html中。 2. 需要处理图片在html中的路径问题,确保图片能够正确展示。 以下是一个简单的示例代码,用于将docx转换为html并处理图片: ```java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.hwpf.usermodel.PictureType; import org.apache.poi.util.IOUtils; import org.w3c.dom.Document; public class DocxToHtmlConverter { public static void main(String[] args) throws Exception { convertDocxToHtml("input.docx", "output.html"); } public static void convertDocxToHtml(String docxPath, String htmlPath) throws Exception { HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(docxPath)); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> { try { File imageFile = File.createTempFile(suggestedName, pictureType.extension); OutputStream out = new FileOutputStream(imageFile); out.write(content); IOUtils.closeQuietly(out); return imageFile.getAbsolutePath(); } catch (IOException e) { return null; } }); wordToHtmlConverter.processDocument(wordDocument); Document htmlDocument = wordToHtmlConverter.getDocument(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource(htmlDocument); StreamResult streamResult = new StreamResult(outStream); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); outStream.close(); String html = new String(outStream.toByteArray()); // 处理图片路径问题 html = html.replaceAll("<img src=\"", "<img src=\"" + new File(docxPath).getParent() + File.separator); FileOutputStream fos = new FileOutputStream(htmlPath); fos.write(html.getBytes()); fos.close(); } } ``` 该代码使用POI的WordToHtmlConverter类将docx文件转换为html,并将图片插入到html中。在处理图片时,采用了PicturesManager接口来实现自定义的图片处理逻辑。在转换完成后,需要将图片路径进行处理,确保图片能够正确展示。 注意:该代码仅是一个简单的示例,可能无法处理所有情况。在实际使用中,还需要根据具体情况进行适当的修改。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值