现在的位置: 首页 > 综合 > 正文

博客备份系统之一:PDF,Word,TXT文件操作类

2012年08月01日 ⁄ 综合 ⁄ 共 13311字 ⁄ 字号 评论关闭

  2011年到了,在前几天的“2010岁末小记”中给自己定下了一个计划,其中有一条就是“每周至少写一篇技术博客。用博客的方式来督促自己学习和进步,记下学习的新知识和积累的知识点,构建自己的知识库。”。园子里高手很多,MVP就有好几位,看他们的文章真有“看君一博文,胜读四年书”之感。曾经对委托、事件云里雾里的我看了张子阳的“C#中的委托和事件”后终于明白了很多,园子里像这样的好文章还有很多,作为菜鸟我真的获益匪浅。

  虽然自己现在水平很差,但高手都是从菜鸟成长起来的,因此我坚信只要努力学习,每天都有收获和进步,逐渐提高自己的编程水平,总有一天也能厚积薄发,写出一些比较好的博文与大家分享,帮助新手进步。作为新年第一篇博文,我打算写一个博客备份系统系列文章与园友们分享,晒晒自己的代码,非常欢迎大家提出意见和建议。

  本文作为此系列的开篇,只写几个后面要用到的重要的类,PDF、Word、TXT文件操作类,其中Word、TXT文件操作类网上很多,这两个类的代码我只直接贴出来,重点说一下PDF文件操作类。

 

  一、PDF文件操作类

  本文PDF文件操作类用iTextSharp控件,这是一个开源项目(http://sourceforge.net/projects/itextsharp/),园子里也有这方面的文章,我的PDF操作类只是做了一点封装,使使用起来更方便。在贴出代码前先对其中几个比较关键的地方作一下说明。

  1、文档的创建

  PDF文档的创建是实例化一个Document对像,有三个构造函数:

         public Document();
         public Document(Rectangle pageSize);
         public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);

  第一个是默认大小,第二个是按给定的大小创建文档,第三个就是按给定的大小创建文档,并且文档内容离左、右、上、下的距离。其中的Rectangle也是iTextSharp中的一个表示矩形的类,这里只用来表示大小。不过要注意的是在向文档里写内容之前还要调用GetInstance方法哦,这个方法传进去一些文档相关信息(如路径,打开方式等)。

 

 

  2、字体的设置

  PDF文件字体在iTextSharp中有两个类,BaseFont和Font,BaseFont是一个抽象类,BaseFont和Font的构造函数如下:

  BaseFont:  

        public static BaseFont CreateFont();
        
public static BaseFont CreateFont(PRIndirectReference fontRef);
        
public static BaseFont CreateFont(string name, string encoding, bool embedded);
        
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool forceRead);
        
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb);
        
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb, bool noThrow);
        
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb, bool noThrow, bool forceRead);

  默认的构造函数用的是英文字体,如果想用中文一般用的是第三个构造函数,这三个参数前两个意思是字体名子或字体资源路径,第三个参数我也没弄明白是什么意思。如果用字体名子其实用的是这个DLL内置字体,如果用字体资源名子可以用系统字体存放路径,如“C:\Windows\Fonts\SIMHEI.TTF”(windows系统),也可以把字体文件放在应用程序目录,然后取这个路径。

  Font:

        public Font();
        
public Font(BaseFont bf);
        
public Font(Font other);
        
public Font(Font.FontFamily family);
        
public Font(BaseFont bf, float size);
        
public Font(Font.FontFamily family, float size);
        
public Font(BaseFont bf, float size, int style);
        
public Font(Font.FontFamily family, float size, int style);
        
public Font(BaseFont bf, float size, int style, BaseColor color);
        
public Font(Font.FontFamily family, float size, int style, BaseColor color);

  一般用的是第五个构造函数,也就是从BaseFont创建,然后设置字体大小。因为iTestSharp在添加文字时字体参数用的都是Font,因些一般的做法是先创建BaseFont对象,再用这个对象加上大小来实例化Font对象。

  3、添加段落

  iTextSharp对段落分了三个级别,从小到大依次为Chunk、Phrase、Paragraph。Chunk : 块,PDF文档中描述的最小原子元,Phrase : 短语,Chunk的集合,Paragraph : 段落,一个有序的Phrase集合。你可以简单地把这三者理解为字符,单词,文章的关系。

  Document对象添加内容的方法为:

        public virtual bool Add(IElement element);

  Chunk、Phrase实现了IElement接口,Paragraph继承自Phrase,因些Document可直接添加这三个对象。

  Paragraph的构造函数是:

        public Paragraph();
        
public Paragraph(Chunk chunk);
        
public Paragraph(float leading);
        
public Paragraph(Phrase phrase);
        
public Paragraph(string str);
        
public Paragraph(float leading, Chunk chunk);
        
public Paragraph(float leading, string str);
        
public Paragraph(string str, Font font);
        
public Paragraph(float leading, string str, Font font);

  大家可以看到Chunk、Phrase都可以实例化Paragraph,不过我用的比较多的是倒数第二个。当然了,Paragraph还有一些属性可以让我们给段落设定一些格式,比如对齐方式,段前空行数,段后空行数,行间距等。 这些属性如下:

        protected int alignment;
        
protected float indentationLeft;
        
protected float indentationRight;
        
protected bool keeptogether;
        
protected float multipliedLeading;
        
protected float spacingAfter;
        
protected float spacingBefore;

  略作解释:alignmant为对齐方式(1为居中,0为居左,2为居右),indentationLeft为左缩进,indentationRight为右缩进,keeptogether保持在一起(常用在对内容绝对定位),multipliedLeading为行间距,spacingAfter为段前空行数,spacingBefore为段后空行数。

  4、内部链接和外部链接

  链接在iTextSharp中有Anchor对象,它有两个属性,name和reference,name自然就是链接的名称了,reference就是链接的地址了,如果是外部链接reference直接就是一个网址,如果是内部链接,就跟html中的锚一样,用'#'加上name名,示例如下:

            //外部链接示例
            Anchor anchor = new Anchor("博客园", font);
            anchor.Reference 
= "http://www.cnblogs.com";
            anchor.Name 
= "博客园";

            //内部链接示例
            Anchor anc1 = new Anchor("This is an internal link test");
            anc1.Name 
= "test";
            Anchor anc2 
= new Anchor("Click here to jump to the internal link test");
            anc2.Reference 
= "#test"

  5、插入图片

  在PDF中插入图片用的是iTextSharp中的Image类。这个类的构造函数很简单:

        public Image(Image image);
        
public Image(Uri url);

  常用的就是用图片的Uri来实例化一个图片。因为这个数继承自Rectangle,而Rectangle又实现了IElement接口,因些可以直接将图片添加到文档中。Image有很多属性用来控制格式,不过常用的也就是对齐方式(Alignment),图片大小的控制了。不过值得一提的就是ScaleAbsolute方法:

        public void ScaleAbsolute(float newWidth, float newHeight);

  看参数就知道是给图片重新设定宽度和高度的,我的做法是如果图片宽度大于文档宽度就按比例缩小,否则不处理:

        /// <summary>
        
/// 添加图片
        
/// </summary>
        
/// <param name="path">图片路径</param>
        
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
        
/// <param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>
        
/// <param name="newHeight">图片高</param>
        public void AddImage(string path, int Alignment, float newWidth, float newHeight)
        {
            Image img 
= Image.GetInstance(path);
            img.Alignment 
= Alignment;
            
if (newWidth != 0)
            {
                img.ScaleAbsolute(newWidth, newHeight);
            }
            
else
            {
                
if (img.Width > PageSize.A4.Width)
                {
                    img.ScaleAbsolute(rect.Width, img.Width 
* img.Height / rect.Height);
                }
            }
            document.Add(img);
        }

  其中的rect是我定义的一个文档大小属性。

  好了,下面就贴出我的PDF文档操作类吧。为了达到封装的目地(这里说的封装意思是调用的类可以不引用iTextSharp这个DLL),我在传参过程中做了一点更改。如设置页面大小时Document的构造函数中提供了用Rectangle对象实例化,但因为这个类是iTextSharp中的,因此我改为传一个字符串(如"A4"),根据这个字符串实例化一个Rectangle对象,再来设置页面大小,其它地方类似。

PDF操作类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace BlogBakLib
{
    
/// <summary>
    
/// PDF文档操作类
    
/// 作者:天行健,自强不息(http://www.cnblogs.com/durongjian
    
/// 创建日期:2011年1月5日
    
/// </summary>
    public class PDFOperation
    {
        
//文档对象
        private Document document;
        
//文档大小
        private Rectangle rect;
        
//字体
        private BaseFont basefont;
        
private Font font;

        /// <summary>
        
/// 构造函数
        
/// </summary>
        public PDFOperation()
        {
            rect 
= PageSize.A4;
            document 
= new Document(rect);
        }

        /// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="type">页面大小(如"A4")</param>
        public PDFOperation(string type)
        {
            SetPageSize(type);
            document 
= new Document(rect);
        }

        /// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="type">页面大小(如"A4")</param>
        
/// <param name="marginLeft">内容距左边框距离</param>
        
/// <param name="marginRight">内容距右边框距离</param>
        
/// <param name="marginTop">内容距上边框距离</param>
        
/// <param name="marginBottom">内容距下边框距离</param>
        public PDFOperation(string type,float marginLeft, float marginRight, float marginTop, float marginBottom)
        {
            SetPageSize(type);
            document 
= new Document(rect,marginLeft,marginRight,marginTop,marginBottom);
        }

        /// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="type">页面大小(如"A4")</param>
        public PDFOperation(string type)
        {
            SetPageSize(type);
            document 
= new Document(rect);
        }

        /// <summary>
        
/// 设置页面大小
        
/// </summary>
        
/// <param name="type">页面大小(如"A4")</param>
        public void SetPageSize(string type)
        {
            
switch (type.Trim())
            {
                
case "A4":
                    rect 
= PageSize.A4;
                    
break;
                
case "A8":
                    rect 
= PageSize.A8;
                    
break;
            }
        }

        /// <summary>
        
/// 设置字体
        
/// </summary>
        public void SetBaseFont(string path)
        {
            basefont 
= BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }

        /// <summary>
        
/// 设置字体
        
/// </summary>
        
/// <param name="size">字体大小</param>
        public void SetFont(float size)
        {
            font 
= new Font(basefont, size);
        }

        /// <summary>
        
/// 实例化文档
        
/// </summary>
        
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
        public void GetInstance(Stream os)
        {
            PdfWriter.GetInstance(document, os);
        }

        /// <summary>
        
/// 打开文档对象
        
/// </summary>
        
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
        public void Open(Stream os)
        {
            GetInstance(os);
            document.Open();
        }

        /// <summary>
        
/// 关闭打开的文档
        
/// </summary>
        public void Close()
        {
            document.Close();
        }

        /// <summary>
        
/// 添加段落
        
/// </summary>
        
/// <param name="content">内容</param>
        
/// <param name="fontsize">字体大小</param>
        public void AddParagraph(string content, float fontsize)
        {
            SetFont(fontsize);
            Paragraph pra 
= new Paragraph(content,font);
            document.Add(pra);
        }

        /// <summary>
        
/// 添加段落
        
/// </summary>
        
/// <param name="content">内容</param>
        
/// <param name="fontsize">字体大小</param>
        
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
        
/// <param name="SpacingAfter">段后空行数(0为默认值)</param>
        
/// <param name="SpacingBefore">段前空行数(0为默认值)</param>
        
/// <param name="MultipliedLeading">行间距(0为默认值)</param>
        public void AddParagraph(string content, float fontsize, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading)
        {
            SetFont(fontsize);
            Paragraph pra 
= new Paragraph(content, font);
            pra.Alignment 
= Alignment;
            
if (SpacingAfter != 0)
            {
                pra.SpacingAfter 
= SpacingAfter;
            }
            
if (SpacingBefore != 0)
            {
                pra.SpacingBefore 
= SpacingBefore;
            }
            
if (MultipliedLeading != 0)
            {
                pra.MultipliedLeading 
= MultipliedLeading;
            }
            document.Add(pra);
        }

        /// <summary>
        
/// 添加链接
        
/// </summary>
        
/// <param name="Content">链接文字</param>
        
/// <param name="FontSize">字体大小</param>
        
/// <param name="Reference">链接地址</param>
        public void AddAnchorReference(string Content, float FontSize, string Reference)
        {
            SetFont(FontSize);
            Anchor auc 
= new Anchor(Content, font);
            auc.Reference 
= Reference;
            document.Add(auc);
        }

        /// <summary>
        
/// 添加链接点
        
/// </summary>
        
/// <param name="Content">链接文字</param>
        
/// <param name="FontSize">字体大小</param>
        
/// <param name="Name">链接点名</param>
        public void AddAnchorName(string Content, float FontSize, string Name)
        {
            SetFont(FontSize);
            Anchor auc 
= new Anchor(Content, font);
            auc.Name 
= Name;
            document.Add(auc);
        }

        /// <summary>
        
/// 添加图片
        
/// </summary>
        
/// <param name="path">图片路径</param>
        
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
        
/// <param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>
        
/// <param name="newHeight">图片高</param>
        public void AddImage(string path, int Alignment, float newWidth, float newHeight)
        {
            Image img 
= Image.GetInstance(path);
            img.Alignment 
= Alignment;
            
if (newWidth != 0)
            {
                img.ScaleAbsolute(newWidth, newHeight);
            }
            
else
            {
                
if (img.Width > PageSize.A4.Width)
                {
                    img.ScaleAbsolute(rect.Width, img.Width 
* img.Height / rect.Height);
                }
            }
            document.Add(img);
        }
    }
}

  好了,PDF操作类就写到这儿吧!因为本人编程是自学的,在编码规范方面可能做的不好,大家对这个类中的代码有什么改进意见请在评论中指出来哦!

  二、WORD文档操作类

  这个就不说了,直接贴代码:  

WORD操作类

using System;   
using System.Collections.Generic;   
using System.Text;   
using System.Drawing; 
using System.IO;

namespace BlogMoveLib   
{
    
public class WordOperation   
    {
        
private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic; 
        
private Microsoft.Office.Interop.Word.Document oDoc;
        
object missing = System.Reflection.Missing.Value;   
  
        
public Microsoft.Office.Interop.Word.ApplicationClass WordApplication   
        {   
            
get { return oWordApplic; }   
        }   
  
        
public WordOperation()   
        {     
            oWordApplic 
= new Microsoft.Office.Interop.Word.ApplicationClass();   
        }

        public WordOperation(Microsoft.Office.Interop.Word.ApplicationClass wordapp)   
        {   
            oWordApplic 
= wordapp;   
        }  
 
        
#region 文件操作   
  
        
// Open a file (the file must exists) and activate it   
        public void Open(string strFileName)   
        {   
            
object fileName = strFileName;
            
object

抱歉!评论已关闭.