c#,将pdf文件转换成图片文件

本文采用Adobe Acrobat9.0的COM组件,将Pdf文件的每一页转换成对应的图片文件。

开发环境:VS2010,.Net Framework4.0,Adobe Acrobat9.0。

工程中添加COM引用:Adobe Acrobat 9.0 Type Library(必须装了Adobe Acrobat9.0才会有)。
思路:

1、需要用到的COM对象:

1)CAcroPDDoc:Acrobat文档对象。

2)CAcroPDPage:页对象。

3)CAcroRect:用来描述页中一个矩形区域的对象。

4)CAcroPoint:实际上代表的是Size。

2、转换过程:

1)打开文档。

2)取出每一页。

3)获取每一页的大小,生成一个表示该页的矩形区域。

4)将当前页的指定区域编码成图片,并且复制到剪贴板中。

5)将剪贴板中的图片取出,保存为图片文件。

转换函数代码:

public static void ConvertPdf2Image(string pdfFilePath, string imageDirectoryPath, int beginPageNum, int endPageNum, ImageFormat format, double zoom = 1)
        {
            Acrobat.CAcroPDDoc pdfDoc = null; Acrobat.CAcroPDPage pdfPage = null; Acrobat.CAcroRect pdfRect = null; Acrobat.CAcroPoint pdfPoint = null;
            //1)       //     生成操作Pdf文件的Com对象       
            pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
            // 检查输入参数             
            if (!pdfDoc.Open(pdfFilePath)) { throw new FileNotFoundException(string.Format("源文件{0}不存在!", pdfFilePath)); }
            if (!Directory.Exists(imageDirectoryPath)) { Directory.CreateDirectory(imageDirectoryPath); }
            if (beginPageNum <= 0) { beginPageNum = 1; }
            if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= 0) { endPageNum = pdfDoc.GetNumPages(); }
            if (beginPageNum > endPageNum) { throw new ArgumentException("参数\"beginPageNum\"必须小于\"endPageNum\"!"); }
            if (format == null) { format = ImageFormat.Png; }
            if (zoom <= 0) { zoom = 1; }
            //转换            
            for (int i = beginPageNum; i <= endPageNum; i++)
            {
                //2)               
                //  取出当前页
                pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i - 1);
                //3)                
                //    得到当前页的大小               
                pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
                // 生成一个页的裁剪区矩形对象            
                pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");
                // 计算当前页经缩放后的实际宽度和高度,zoom==1时,保持原比例大小   
                int imgWidth = (int)((double)pdfPoint.x * zoom); int imgHeight = (int)((double)pdfPoint.y * zoom);
                //设置裁剪矩形的大小为当前页的大小             
                pdfRect.Left = 0; pdfRect.right = (short)imgWidth; pdfRect.Top = 0; pdfRect.bottom = (short)imgHeight;
                //4)                
                //    将当前页的裁剪区的内容编成图片后复制到剪贴板中            
                pdfPage.CopyToClipboard(pdfRect, 0, 0, (short)(100 * zoom));
                // 5)             
                IDataObject clipboardData = Clipboard.GetDataObject();
                //检查剪贴板中的对象是否是图片,如果是图片则将其保存为指定格式的图片文件   
                if (clipboardData.GetDataPresent(DataFormats.Bitmap))
                {
                    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
                    pdfBitmap.Save(Path.Combine(imageDirectoryPath, i.ToString("0000") + "." + format.ToString()), format);
                    pdfBitmap.Dispose();
                }

            }
            // 关闭和释放相关COM对象 
            pdfDoc.Close(); Marshal.ReleaseComObject(pdfRect);
            Marshal.ReleaseComObject(pdfPoint);
            Marshal.ReleaseComObject(pdfPage);
            Marshal.ReleaseComObject(pdfDoc);
        }

代码:

http://download.csdn.net/download/kongxh_1981/9161481

网上有一篇搜集的非常全的将Pdf文件转换成图片的各种方法,拿出来分享:

http://topic.csdn.net/u/20120219/20/4888d128-3b77-47bc-aa21-cb02c014bc1f.html?84661

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用第三方库iTextSharp来将OFD文件转换成PDF文件。首先需要将OFD文件解压缩,然后将解压缩后的XML文件转换成PDF文件。 以下是一个示例代码: ```csharp using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using System.Xml; public static void ConvertOFDToPDF(string ofdFilePath, string pdfFilePath) { // 解压缩OFD文件 string tempFolderPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempFolderPath); ZipFile.ExtractToDirectory(ofdFilePath, tempFolderPath); // 获取OFD文档的页面尺寸 string documentXmlPath = Path.Combine(tempFolderPath, "Documents", "Document.xml"); XmlDocument documentXml = new XmlDocument(); documentXml.Load(documentXmlPath); XmlNamespaceManager nsManager = new XmlNamespaceManager(documentXml.NameTable); nsManager.AddNamespace("ofd", "http://www.ofdspec.org"); XmlNode pageAreaNode = documentXml.SelectSingleNode("/ofd:Document/ofd:Pages/ofd:PageArea", nsManager); float pageWidth = float.Parse(pageAreaNode.Attributes["PageWidth"].Value); float pageHeight = float.Parse(pageAreaNode.Attributes["PageHeight"].Value); // 创建PDF文档 using (FileStream pdfFileStream = new FileStream(pdfFilePath, FileMode.Create)) { using (Document pdfDocument = new Document(new Rectangle(pageWidth, pageHeight))) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, pdfFileStream)) { pdfDocument.Open(); // 遍历OFD文档的页面,将每个页面转换成PDF页面 XmlNodeList pageNodes = documentXml.SelectNodes("/ofd:Document/ofd:Pages/ofd:Page", nsManager); foreach (XmlNode pageNode in pageNodes) { string pageFileNodeValue = pageNode.Attributes["BaseLoc"].Value; string pageFilePath = Path.Combine(tempFolderPath, pageFileNodeValue); using (FileStream pageFileStream = new FileStream(pageFilePath, FileMode.Open)) { using (MemoryStream pageMemoryStream = new MemoryStream()) { pageFileStream.CopyTo(pageMemoryStream); byte[] pageBytes = pageMemoryStream.ToArray(); // 将OFD页面转换成PDF页面 using (MemoryStream pdfMemoryStream = new MemoryStream()) { using (Document pageDocument = new Document()) { using (PdfWriter pdfPageWriter = PdfWriter.GetInstance(pageDocument, pdfMemoryStream)) { pageDocument.Open(); using (MemoryStream pageXmlStream = new MemoryStream(pageBytes)) { XmlDocument pageXml = new XmlDocument(); pageXml.Load(pageXmlStream); XmlNode pageContentNode = pageXml.SelectSingleNode("/ofd:Page/ofd:Content", nsManager); string pageContent = pageContentNode.InnerXml; using (MemoryStream pageContentStream = new MemoryStream()) { using (StreamWriter pageContentWriter = new StreamWriter(pageContentStream)) { pageContentWriter.Write(pageContent); pageContentWriter.Flush(); pageContentStream.Position = 0; XmlParserContext xmlParserContext = new XmlParserContext(null, nsManager, null, XmlSpace.None); XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); xmlReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader xmlReader = XmlReader.Create(pageContentStream, xmlReaderSettings, xmlParserContext)) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { string elementName = xmlReader.Name; if (elementName == "ofd:TextObject") { string fontId = xmlReader.GetAttribute("Font"); string fontSizeString = xmlReader.GetAttribute("Size"); float fontSize = float.Parse(fontSizeString); string fontFamily = null; XmlNode fontNode = documentXml.SelectSingleNode($"/ofd:Document/ofd:Fonts/ofd:Font[@ID='{fontId}']", nsManager); if (fontNode != null) { fontFamily = fontNode.Attributes["FontName"].Value; } if (string.IsNullOrEmpty(fontFamily)) { fontFamily = "宋体"; } BaseFont baseFont = BaseFont.CreateFont($"{fontFamily},Bold", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont, fontSize); string text = xmlReader.ReadElementContentAsString(); pdfDocument.Add(new Paragraph(text, font)); } else if (elementName == "ofd:PathObject") { // 处理OFD路径对象 } else if (elementName == "ofd:ImageObject") { // 处理OFD图像对象 } } } } } } } pageDocument.Close(); } } byte[] pdfBytes = pdfMemoryStream.ToArray(); PdfReader pdfReader = new PdfReader(pdfBytes); pdfWriter.DirectContent.AddTemplate(pdfWriter.GetImportedPage(pdfReader, 1), 0, 0); } } } } pdfDocument.Close(); } } } Directory.Delete(tempFolderPath, true); } ``` 请注意,这段代码只是一个示例,可能需要根据你的具体情况进行修改和调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值