日期:2014-05-17  浏览次数:20887 次

C#如何将word文档转为pdf或者图片
请问如果不使用任何第三方dll,有没有办法将word文档(2003版)转为pdf或者图片?

------解决方案--------------------
不用任何第三方库,当然也是可以的啊,而且随便就可以搜到的好么。。。
我姑且简单写一下吧
1、office需要2007或以上
2、微软自己有一个office组件,可以将word(其他excel什么的好像也行,忘了)保存成xps或pdf,名字忘了,不过很容易找到的,总之找来装上
3、如果转pdf,Open以后直接调用_Document的ExportAsFixedFormat,第二个参数用WdExportFormat.wdExportFormatPDF,就行了
4、如果转图片,麻烦一点,先用3的方法转xps,然后

        Bitmap image = null;
        FixedDocumentSequence docs = xps.GetFixedDocumentSequence();
        using (DocumentPage docPage = docs.DocumentPaginator.GetPage(page))
        {
            float dpi = ConfigManager.DocDpi;
            int width = (int)(docPage.Size.Width * dpi / 96 + 0.5);
            int height = (int)(docPage.Size.Height * dpi / 96 + 0.5);

            RenderTargetBitmap renderTarget = new RenderTargetBitmap(width, height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
            renderTarget.Render(docPage.Visual);

            // calling GetPage without calling UpdateLayout causes a memory leak
            ((FixedPage)docPage.Visual).UpdateLayout();

            BitmapEncoder encoder = new BmpBitmapEncoder();  // Choose type here ie: JpegBitmapEncoder, etc  
            encoder.Frames.Add(BitmapFrame.Create(renderTarget));

            MemoryStream s = new MemoryStream();
            encoder.Save(s);
            image = new Bitmap(s);
            image.SetResolution(dpi, dpi);
        }

大致是这样,dpi根据你实际情况设,默认是96

另外,楼上有人提到的Spire的那个库我用过,简单试个1、2页看起来很不错,速度还快一些,可试个50页的有文字图片表格的word,转成图片跟原始word区别就很大了,会发现分页都不对,导致最后可能只有49页,这个我当时还到他们论坛发帖问,然后官方回复说他