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

本文关键字:图像 HTML 转换 TIKA word 文档 通过 | 更新日期: 2023-09-27 17:58:32

我是TIKA的新手。我尝试使用Tika将Microsoft word文档转换为HTML。我使用TikaOnDotNet包装器来使用TIKA-on-Net框架。我的转换代码如下:

        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包含图像标签,如:

<img src="embedded:image2.wmf" alt="image2.wmf"/>

但是图像源不存在。请通知我

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

学分转到@Gagravarr。

请注意,这是一个简单的代码实现,原始代码可用于评论问题。

此实现基于TikaOnDotNet包装器。。。。。

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;
            }
        }
    }
}