首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过TIKA将word文档转换为带有嵌入图像的HTML

通过TIKA将word文档转换为带有嵌入图像的HTML
EN

Stack Overflow用户
提问于 2016-07-25 21:09:50
回答 1查看 2.3K关注 0票数 3

我是蒂卡新来的。我尝试使用Tika将Microsoft文档转换为HTML。我使用TikaOnDotNet包装器在.Net框架上使用TIKA。我的转换代码如下所示:

代码语言:javascript
复制
        byte[] file = Files.toByteArray(new File(@"myPath\document.doc"));
        AutoDetectParser tikaParser = new AutoDetectParser();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
        TransformerHandler handler = factory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        handler.setResult(new StreamResult(output));

        ExpandedTitleContentHandler handler1 = new ExpandedTitleContentHandler(handler);

        tikaParser.parse(new ByteArrayInputStream(file), handler1, new Metadata());


        File ofile = new File(@"C:\toHtml\text.html");
        ofile.createNewFile();
        DataOutputStream stream = new DataOutputStream(new FileOutputStream(ofile));
        output.writeTo(stream);

一切正常,除了嵌入的图像。生成的HTML包含如下图像标记:

代码语言:javascript
复制
<img src="embedded:image2.wmf" alt="image2.wmf"/>

但是图像源并不存在。请告诉我

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-26 18:54:44

学分是@Gagravarr。

请注意,这是一个简单的代码实现,原代码可在评论中提出问题。

该实现基于TikaOnDotNet包装器.

代码语言:javascript
复制
public class DocToHtml
{

    private TikaConfig config = TikaConfig.getDefaultConfig();
    public void Convert()
    {

        byte[] file = Files.toByteArray(new File(@"filename.doc"));
        AutoDetectParser tikaParser = new AutoDetectParser();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
        var inputStream = new ByteArrayInputStream(file);
        //           ToHTMLContentHandler handler = new ToHTMLContentHandler();
        var metaData = new Metadata();
        EncodingDetector encodingDetector = new UniversalEncodingDetector();
        var encode = encodingDetector.detect(inputStream, metaData) ?? new UTF_32();
        TransformerHandler handler = factory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encode.toString());
        handler.setResult(new StreamResult(output));

        ContentHandler imageRewriting = new ImageRewritingContentHandler(handler); 

        //  ExpandedTitleContentHandler handler1 = new ExpandedTitleContentHandler(handler);
        ParseContext context = new ParseContext();
        context.set(typeof(EmbeddedDocumentExtractor), new FileEmbeddedDocumentEtractor());

        tikaParser.parse(inputStream, imageRewriting, new Metadata(), context);


        byte[] array =  output.toByteArray();

       System.IO.File.WriteAllBytes(@"C:\toHtml\text.html", array);

    }


    private class ImageRewritingContentHandler : ContentHandlerDecorator
    {
        public ImageRewritingContentHandler(ContentHandler handler) : base(handler)
        {
        }

        public override void startElement(string uri, string localName, string name, Attributes origAttrs)
        {
            if ("img".Equals(localName))
            {
                AttributesImpl attrs;
                if (origAttrs is AttributesImpl)
                    attrs = (AttributesImpl)origAttrs;
                else
                    attrs = new AttributesImpl(origAttrs);



                for (int i = 0; i < attrs.getLength(); i++)
                {
                    if ("src".Equals(attrs.getLocalName(i)))
                    {
                        String src = attrs.getValue(i);
                        if (src.StartsWith("embedded:"))
                        {
                            var newSrc = src.Replace("embedded:", @"images\");

                            attrs.setValue(i, newSrc);
                        }
                    }
                }
                attrs.addAttribute(null, "width", "width","width", "100px");
                base.startElement(uri, localName, name, attrs);
            }
            else
                base.startElement(uri, localName, name, origAttrs);
        }
    }

    private class FileEmbeddedDocumentEtractor : EmbeddedDocumentExtractor
    {
        private int count = 0;
        public bool shouldParseEmbedded(Metadata m)
        {
            return true;
        }

        public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler, Metadata metadata, bool outputHtml)
        {
            Detector detector = new DefaultDetector();
            string name = metadata.get("resourceName");
            MediaType contentType = detector.detect(inputStream, metadata);
            if (contentType.getType() != "image") return;
            var embeddedFile = name;
            File outputFile = new File(@"C:\toHtml\images", embeddedFile);
            try
            {
                using (FileOutputStream os = new FileOutputStream(outputFile))
                {
                    var tin = inputStream as TikaInputStream;
                    if (tin != null)
                    {
                        if (tin.getOpenContainer() != null && tin.getOpenContainer() is DirectoryEntry)
                        {
                            POIFSFileSystem fs = new POIFSFileSystem();

                            fs.writeFilesystem(os);
                        }
                        else
                        {
                            IOUtils.copy(inputStream, os);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38577468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档