C#简单实现office转pdf、pdf转图片

http://www.2cto.com/kf/201110/107592.html

国庆放假前,公司有个项目里要用到office、pdf以及图片的互转,自己以前没有接触过,所以整理了网上林林总总的办法,也算是总结出了最简单有效的办法:office -> pdf 应用Adobe Acrobat 8 Pro的一个PDFMakerAPI.dll程序集;pdf -> png(jpg,gif...)应用Ghostscript。下面详述说明:

一、准备工作:

1.安装Adobe Acrobat 8 Pro,本人安装的是8.1.2版本,在你的安装目录下(例如我自己的:C:\Program Files\Adobe\Acrobat 8.0\PDFMaker\Common\)common目录中找到PDFMakerAPI.dll程序集,拷贝出到项目中放DLL的文件夹(此文件夹为用户保存DLL文件的文件夹,名称以自己项目为准),并在项目里对其添加引用。

2.安装Ghostscript,本人安装的是8.63版本,需要用的的其他DLL:FontBox-0.1.0-dev.dll,IKVM.GNU.Classpath.dll,IKVM.Runtime.dll,PDFBox-0.7.3.dll,其中IKVM.GNU.Classpath.dll,PDFBox-0.7.3.dll要在项目里对其添加引用,其他两个(4个dll均放到)放到DLL文件夹里即可。

3.为Ghostscript配置Web.config:

<appSettings>
    <add key="GhostScriptView" value="C:/Program Files/gs/gs8.63/bin"/>
    <add key="GhostScriptArguments" value="-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4"/>
</appSettings>

找到自己对应的Ghostscript安装目录,自行修改。

二、应用:

1.office -> pdf

引用命名空间:using PDFMAKERAPILib;关键代码如下:

1 /// 

2 ///参数:docfile,源office文件绝对路径及文件名(C:\office\myDoc.doc);printpath,pdf文件保存路径(D:\myPdf);printFileName,保 

3 ///存pdf文件的文件名(myNewPdf.pdf) 

4 /// 

5   

6  objectmissing = System.Type.Missing; 

7  PDFMakerAppapp = new PDFMakerApp(); 

8  app.CreatePDF(docfile, printpath + printFileName, PDFMakerSettings.kConvertAllPages, false, true, true, missing);

2.pdf-> 图片

引用命名空间:using org.pdfbox.pdmodel;关键代码如下:

01 /// 

02 /// <param name="pdfFile">PDF文档物理路径</param> 

03 /// <param name="imgPath">转换成的图片文件的存放物理路径</param> 

04 /// 

05        public static void PdfToImages(string pdfFile, string imgPath) 

06         { 

07             PDDocument doc = PDDocument.load(pdfFile); 

08             int pageCount = doc.getDocumentCatalog().getAllPages().size();//计算pdf文档的总页数 

09   

10             string pdfFileName = Path.GetFileName(pdfFile); 

11             int index = pdfFileName.LastIndexOf('.'); 

12             if (index != -1) 

13                 pdfFileName = pdfFileName.Substring(0, index); 

14   

15             string imgFile = Path.Combine(imgPath, pdfFileName);//转换成的图片文件 

16   

17             if (pageCount == 0) return; 

18             if (pageCount == 1) 

19             { 

20                 imgFile += ".png"; 

21                 if (File.Exists(imgFile)) 

22                 { 

23                     File.Delete(imgFile); 

24                 } 

25             } 

26             else

27             { 

28                 for (int i = 0; i < pageCount; i++) 

29                 { 

30                     string _imgFile = imgFile + (i + 1).ToString() + ".png"; 

31                     if (File.Exists(_imgFile)) 

32                     { 

33                         File.Delete(_imgFile); 

34                     } 

35                 } 

36                 imgFile += "%d.png"; 

37             } 

38   

39             ProcessStartInfo info = new ProcessStartInfo(); 

40             info.CreateNoWindow = true; 

41             info.WindowStyle = ProcessWindowStyle.Hidden; 

42             info.WorkingDirectory = System.Configuration.ConfigurationManager.AppSettings["GhostScriptView"]; 

43             info.Arguments = System.Configuration.ConfigurationManager.AppSettings["GhostScriptArguments"] + @" -sOutputFile=" + imgFile + "  " + pdfFile; 

44             info.FileName = @"gswin32c.exe"; 

45             Process subProcess = new Process(); 

46             subProcess.StartInfo = info; 

47             subProcess.Start(); 

48             subProcess.WaitForExit(int.MaxValue); 

49         }

完成上述几步即可简便完美的完成office到彩色图片的转换,大家不妨也试试。

3.总结和说明:

Acrobat 8 Pro需要激活和注册;

Acrobat 8 Pro生成pdf的时候会有自己的虚拟打印机弹出框,当office文件为ppt或者xls的时候会打开文件然后再关闭,doc则不会;

office转换的pdf存放路径不要带有中文;

最后:如有程序安装包和DLL需求消息我就可以了,祝大家工作愉快

 

摘自:小宝LOVE继艾斯

 

 

 

 

 

 

 

 

http://blog.csdn.net/musical_insect/article/details/5765098

在网上找遍了有关 C# 如何将PDF文档转换成图片的资料,最终在CSDN上面得到了一位高手的指点,根据他的指点,我做了这个项目,希望这个项目能对和我之前有同样需求的人有所帮助!

1、项目中用到了GhostScript,有关GhostScript的详细说明,请参考:http://downloads.sourceforge.net/ghostscript/gs861w32.exe?modtime=1196280996&big_mirror=1

2、在运行本项目前,你必须确保在本地计算机上已安装GhostScript,至于GhostScript的安装目录你可随意选择,但在项目中的配置文件中的<add key="GhostScriptView" value="C:/Program Files/gs/gs8.71/bin"/>也要和你的安装目录同步。

3、根目录中的 gs871w32.exe 为 GhostScript 安装文件,可直点击安装到本地计算机。

4、根目录中还有 IKVM.GNU.Classpath.dll、PDFBox-0.7.3.dll、IKVM.Runtime.dll、FontBox-0.1.0-dev.dll 这四个程序集文件,它们是PDFBox(有关PDFBox的详细说明请参考:http://sourceforge.net/projects/pdfbox/)中的程序集文件,主要用于辅助操作pdf文档,因为使用PDFBox将PDF文档转为图片的.net版本目前还有些BUG,所以在项目中用了GhostScript来实现转换。请将 IKVM.GNU.Classpath.dll、PDFBox-0.7.3.dll引入项目中,再把 IKVM.Runtime.dll、FontBox-0.1.0-dev.dll置于运行目录下,具体请看项目及其代码。

 

项目很简单,下面贴出了主要的代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Diagnostics;
using org.pdfbox.util;
using org.pdfbox.pdmodel;

 

        #region 转换PDF文档

        /// <summary>
        /// 将PDF文档转换成文本
        /// </summary>
        /// <param name="pdfFile">PDF文档物理路径</param>
        /// <returns>返回从PDF文档剥离的文本</returns>
        public string PdfToText(string pdfFile)
        {
            PDDocument doc = PDDocument.load(pdfFile);
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(doc);
        }

        /// <summary>
        /// 将PDF文档转换成图片
        /// </summary>
        /// <param name="pdfFile">PDF文档物理路径</param>
        /// <param name="imgPath">转换成的图片文件的存放物理路径</param>
        /// <param name="isDeletePDF">转换成图片文件以后是否删除原PDF文档</param>
        /// <returns>返回转换成的图片文件物理路径的集合</returns>
        public IList<string> PdfToImages(string pdfFile, string imgPath, bool isDeletePDF)
        {
            IList<string> imgList = new List<string>();
            PDDocument doc = PDDocument.load(pdfFile);
            int pageCount = doc.getDocumentCatalog().getAllPages().size();//计算pdf文档的总页数

            string pdfFileName = Path.GetFileName(pdfFile);
            int index = pdfFileName.LastIndexOf('.');
            if (index != -1)
                pdfFileName = pdfFileName.Substring(0, index);

            string imgFile = Path.Combine(imgPath, pdfFileName);//转换成的图片文件

            if (pageCount == 0) return null;
            if (pageCount == 1)
            {
                imgFile += ".jpg";
                imgList.Add(imgFile);
                if (File.Exists(imgFile)) File.Delete(imgFile);
            }
            else
            {
                for (int i = 0; i < pageCount; i++)
                {
                    string _imgFile = imgFile + (i + 1).ToString() + ".jpg";
                    imgList.Add(_imgFile);
                    if (File.Exists(_imgFile)) File.Delete(_imgFile);
                }
                imgFile += "%d.jpg";
            }

            ProcessStartInfo info = new ProcessStartInfo();
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.WorkingDirectory = System.Configuration.ConfigurationManager.AppSettings["GhostScriptView"];
            info.Arguments = System.Configuration.ConfigurationManager.AppSettings["GhostScriptArguments"] + @" -sOutputFile=" + imgFile + "  " + pdfFile;
            info.FileName = @"gswin32c.exe";
            Process subProcess = new Process();
            subProcess.StartInfo = info;
            subProcess.Start();
            subProcess.WaitForExit(int.MaxValue);
            if (isDeletePDF)
            {
                File.Delete(pdfFile);
            }

            return imgList;
        }

        #endregion

 

代码中会用到的配置信息:

<appSettings>
  <add key="GhostScriptView" value="C:/Program Files/gs/gs8.71/bin"/>
  <add key="GhostScriptArguments" value="-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4"/>
 </appSettings>

 

简单吧,下面请看看本项目运行的效果图:

 

 注:完整项目解决方案我已上传为资源,欢迎大家前去下载使用!

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用第三方库来实现ExcelPDF,比如使用EPPlus和iTextSharp库。 EPPlus是一个用于读写Excel文件的.NET库,支持Excel2007及以上版本,可以读取和写入Excel文件,还支持将Excel文件换为PDF。使用EPPlus库换Excel文件时,需要先将Excel文件加载到内存中,然后再将其换为PDF。 iTextSharp是一个用于生成PDF文档的.NET库,支持将HTML、XML、文本和图像等格式换为PDF。使用iTextSharp库换Excel文件时,需要将Excel文件换为HTML格式,然后再使用iTextSharp将HTML换为PDF。 以下是使用EPPlus库将Excel文件换为PDF文件的示例代码: ```csharp using OfficeOpenXml; using System.IO; public void ConvertExcelToPdf(string excelFilePath, string pdfFilePath) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 需要设置许可证上下文 using (var excelPackage = new ExcelPackage(new FileInfo(excelFilePath))) { var pdfStream = new MemoryStream(); excelPackage.SaveAs(pdfStream, ExcelPackage.ExcelType.Pdf); File.WriteAllBytes(pdfFilePath, pdfStream.ToArray()); } } ``` 以下是使用iTextSharp库将HTML文件换为PDF文件的示例代码: ```csharp using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; public void ConvertHtmlToPdf(string htmlFilePath, string pdfFilePath) { using (var htmlStream = new FileStream(htmlFilePath, FileMode.Open, FileAccess.Read)) using (var pdfStream = new FileStream(pdfFilePath, FileMode.Create, FileAccess.Write)) { var document = new Document(); var writer = PdfWriter.GetInstance(document, pdfStream); document.Open(); XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlStream, null, Encoding.UTF8); document.Close(); } } ``` 需要注意的是,使用第三方库进行ExcelPDF操作可能会存在一些兼容性问题,因此需要根据具体情况进行调试和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值