C#如何将word文档转为pdf或者图片

夏夜花花的太阳 2014-01-02 04:20:09
请问如果不使用任何第三方dll,有没有办法将word文档(2003版)转为pdf或者图片?
...全文
1912 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
arronwalll 2016-03-17
  • 打赏
  • 举报
回复
我觉得要是有个pdf converter支持批量的pdf to image conversion还是挺不错的!
just_swizard 2014-01-03
  • 打赏
  • 举报
回复
不用任何第三方库,当然也是可以的啊,而且随便就可以搜到的好么。。。 我姑且简单写一下吧 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页,这个我当时还到他们论坛发帖问,然后官方回复说他们分页算法也是自己摸索的,所以跟原版有差别也没办法,只能慢慢调~~~
just_swizard 2014-01-03
  • 打赏
  • 举报
回复
引用 11 楼 mickwen10 的回复:
[quote=引用 5 楼 just_swizard 的回复:] 另外,楼上有人提到的Spire的那个库我用过,简单试个1、2页看起来很不错,速度还快一些,可试个50页的有文字图片表格的word,转成图片跟原始word区别就很大了,会发现分页都不对,导致最后可能只有49页,这个我当时还到他们论坛发帖问,然后官方回复说他们分页算法也是自己摸索的,所以跟原版有差别也没办法,只能慢慢调~~~
我用最新版本的感觉分页好像没啥问题哈。[/quote] http://www.e-iceblue.com/forum/problems-about-convert-doc-to-bmp-t4508.html 当时的帖子,你有心的话可以把我当时的测试文档跑一下试试看。 当然我是希望他们真的这么效率3个月不到就解决了这个问题,如果真的这样,我的项目可能也可以重新考虑使用这个库
  • 打赏
  • 举报
回复
引用 10 楼 xiezhongjun 的回复:
itextsharp 先是上网上下载itextsharp.dll,然后引用下面的代码,你可以慢慢测试 代码 public void setBitmap() { using (WebBrowser wb = new WebBrowser()) { wb.Width = w; wb.Height = h; wb.ScrollBarsEnabled = false; wb.Navigate(url); //确保页面被解析完全 while (wb.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } bitmap = new System.Drawing.Bitmap(w, h); wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, w, h)); wb.Dispose(); } } private void CreatPdf(string fileName) { Document doc = new Document(PageSize.A4, 0, 0, 0, 0);//左右上下 MemoryStream ms = new MemoryStream(); try { PdfWriter writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); url = Server.MapPath(fileName + ".html").Replace("My","Upfile"); Thread thread = new Thread(new ThreadStart(setBitmap)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); while (thread.IsAlive) Thread.Sleep(100); string savePath = (url.Replace(".html","") + ".jpg"); bitmap.Save(savePath); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp); img.ScalePercent(59);//560 630 doc.Add(img); } catch (Exception err) { throw new Exception(err.Message); } finally { doc.Close(); using (FileStream fs = new FileStream(url.Replace(".html", "") + ".pdf", FileMode.Create)) { ms.Position = 0; byte[] bit = new byte[ms.Length]; ms.Read(bit, 0, (int)ms.Length); fs.Write(bit, 0, bit.Length); } // ViewPdf(ms, url); } } private void ViewPdf(Stream fs,string url) { Response.Clear(); //中文名的话 //Response.AppendHeader("Content-Disposition", "attachment;filename=" + // HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.AddHeader("Content-Disposition", "attachment;FileName=" + url.Replace(".html", "") + ".pdf"); Response.AddHeader("Content-Length", fs.Length.ToString()); Response.ContentType = "application/pdf"; long fileLength = fs.Length; int size = 10240;//10K一--分块下载,10K为1块 byte[] readData = new byte[size]; if (size > fileLength) size = Convert.ToInt32(fileLength); long fPos = 0; bool isEnd = false; while (!isEnd) { if ((fPos + size) >= fileLength) { size = Convert.ToInt32(fileLength - fPos); isEnd = true; } readData = new byte[size]; fs.Position = fPos; fs.Read(readData, 0, size); Response.BinaryWrite(readData); Response.OutputStream.Flush(); fPos += size; } fs.Close(); Response.OutputStream.Close(); Response.End(); Response.Close(); } 调用 CreatPdf(RateOrderNo);
这个我用过,可是现在我不用dll能实现么?
mickwen10 2014-01-03
  • 打赏
  • 举报
回复
引用 5 楼 just_swizard 的回复:
另外,楼上有人提到的Spire的那个库我用过,简单试个1、2页看起来很不错,速度还快一些,可试个50页的有文字图片表格的word,转成图片跟原始word区别就很大了,会发现分页都不对,导致最后可能只有49页,这个我当时还到他们论坛发帖问,然后官方回复说他们分页算法也是自己摸索的,所以跟原版有差别也没办法,只能慢慢调~~~
我用最新版本的感觉分页好像没啥问题哈。
aellonxie 2014-01-03
  • 打赏
  • 举报
回复
itextsharp 先是上网上下载itextsharp.dll,然后引用下面的代码,你可以慢慢测试 代码 public void setBitmap() { using (WebBrowser wb = new WebBrowser()) { wb.Width = w; wb.Height = h; wb.ScrollBarsEnabled = false; wb.Navigate(url); //确保页面被解析完全 while (wb.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } bitmap = new System.Drawing.Bitmap(w, h); wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, w, h)); wb.Dispose(); } } private void CreatPdf(string fileName) { Document doc = new Document(PageSize.A4, 0, 0, 0, 0);//左右上下 MemoryStream ms = new MemoryStream(); try { PdfWriter writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); url = Server.MapPath(fileName + ".html").Replace("My","Upfile"); Thread thread = new Thread(new ThreadStart(setBitmap)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); while (thread.IsAlive) Thread.Sleep(100); string savePath = (url.Replace(".html","") + ".jpg"); bitmap.Save(savePath); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp); img.ScalePercent(59);//560 630 doc.Add(img); } catch (Exception err) { throw new Exception(err.Message); } finally { doc.Close(); using (FileStream fs = new FileStream(url.Replace(".html", "") + ".pdf", FileMode.Create)) { ms.Position = 0; byte[] bit = new byte[ms.Length]; ms.Read(bit, 0, (int)ms.Length); fs.Write(bit, 0, bit.Length); } // ViewPdf(ms, url); } } private void ViewPdf(Stream fs,string url) { Response.Clear(); //中文名的话 //Response.AppendHeader("Content-Disposition", "attachment;filename=" + // HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.AddHeader("Content-Disposition", "attachment;FileName=" + url.Replace(".html", "") + ".pdf"); Response.AddHeader("Content-Length", fs.Length.ToString()); Response.ContentType = "application/pdf"; long fileLength = fs.Length; int size = 10240;//10K一--分块下载,10K为1块 byte[] readData = new byte[size]; if (size > fileLength) size = Convert.ToInt32(fileLength); long fPos = 0; bool isEnd = false; while (!isEnd) { if ((fPos + size) >= fileLength) { size = Convert.ToInt32(fileLength - fPos); isEnd = true; } readData = new byte[size]; fs.Position = fPos; fs.Read(readData, 0, size); Response.BinaryWrite(readData); Response.OutputStream.Flush(); fPos += size; } fs.Close(); Response.OutputStream.Close(); Response.End(); Response.Close(); } 调用 CreatPdf(RateOrderNo);
  • 打赏
  • 举报
回复
可是我只想做2003的word转成pdf,不使用第三方dll,不使用虚拟打印机,能实现么?
  • 打赏
  • 举报
回复
可惜如果是office2003就实现不了了。 网上只有2007及以上版本的。
bigstone01 2014-01-03
  • 打赏
  • 举报
回复
引用 5 楼 just_swizard 的回复:
不用任何第三方库,当然也是可以的啊,而且随便就可以搜到的好么。。。 我姑且简单写一下吧 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页,这个我当时还到他们论坛发帖问,然后官方回复说他们分页算法也是自己摸索的,所以跟原版有差别也没办法,只能慢慢调~~~
直接调用Office还是会存在一些局限,Office是基于COM方式,.NET调用会存在一些不稳定的情况。特别是在ASP.NET环境,微软也不推荐这样调用,如果是桌面的交互程序可以考虑这种方式,前提是必须安装Office. 微软官方解释, http://support.microsoft.com/kb/257757/zh-cn 大概意思是不推荐在服务器上使用office自动化。
bigstone01 2014-01-03
  • 打赏
  • 举报
回复
引用 4 楼 u013104783 的回复:
[quote=引用 3 楼 u013100360 的回复:] 如果不使用三方控件那很难,
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\TestSample.docx");

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);
http://www.e-iceblue.com/Introduce/word-for-net-introduce.html
这样生成的文档其实还是错的。[/quote] 是生成的文档结果有问题?
  • 打赏
  • 举报
回复
╮(╯▽╰)╭,怎么办啦~
MOMOKA 2014-01-03
  • 打赏
  • 举报
回复
能够提供具体的第三方DLL和使用方法吗?
  • 打赏
  • 举报
回复
引用 3 楼 u013100360 的回复:
如果不使用三方控件那很难,
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\TestSample.docx");

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);
http://www.e-iceblue.com/Introduce/word-for-net-introduce.html
这样生成的文档其实还是错的。
bigstone01 2014-01-02
  • 打赏
  • 举报
回复
如果不使用三方控件那很难,
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\TestSample.docx");

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);
http://www.e-iceblue.com/Introduce/word-for-net-introduce.html
  • 打赏
  • 举报
回复
引用 1 楼 qyj2009 的回复:
不适应任何第三方 那就自己做个DLL就可以了
怎么做呢,我就是代码写不出来。
水目 2014-01-02
  • 打赏
  • 举报
回复
不适应任何第三方 那就自己做个DLL就可以了

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧