HTML текстовая строка для преобразования файла .doc - PullRequest
0 голосов
/ 22 января 2019

У меня есть строковая переменная, которая содержит отформатированный HTML-текст, и мне нужно преобразовать ее в файл .doc с помощью apache-poi.

Я получил это решение, используя docx4j для файла .docx, но клиент хочетРешение с помощью apache-poi, который является html-строкой для преобразования .doc и .docx.

Как конвертировать текстовую строку html в файл .doc и .docx из отформатированной текстовой строки html с помощью apache-poi при весенней загрузке?

Редактировать: solutions-

Для документов:

private String getDocHtmlText(byte[] contents)
            throws FileNotFoundException, IOException, ParserConfigurationException, TransformerConfigurationException,
            TransformerFactoryConfigurationError, TransformerException {
        File file = new java.io.File("reportTemplate.doc");
        FileUtils.writeByteArrayToFile(file, contents);
        InputStream input = new FileInputStream(file);
        HWPFDocument wordDocument = new HWPFDocument(input);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        WordToHtmlConverter converter = new WordToHtmlConverter(doc);
        converter.processDocument(wordDocument);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            DOMSource domSource = new DOMSource(converter.getDocument());
            StreamResult streamResult = new StreamResult(output);
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
        } finally {
            input.close();
            output.close();
            file.delete();
        }
        return output.toString();
    }

Для документов:

private String getDocxHtmlText(byte[] contents) throws IOException, FileNotFoundException {
        File file = new java.io.File("reportTemplate.docx");
        FileUtils.writeByteArrayToFile(file, contents);
        InputStream in = new FileInputStream(file);
        XWPFDocument document = new XWPFDocument(in);
        XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("word/media")));
        OutputStream out = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, out, options);
        in.close();
        out.close();
        file.delete();
        return out.toString();
    }
...