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

【分享】iTextSharp转pdf
 前面发了一篇文件转pdf的帖子
http://topic.csdn.net/u/20100825/21/E116A4A1-5C79-4CB2-9D44-DFADEE57596A.html
那只是个雏形,调用虚拟打印机来实现,office文件转pdf时还依赖于COM组件,在服务器部署时还需要装office的一些组件,现这个版本比较完善,完全基于开源组件iTextSharp来实现把文件转pdf,现把源码放出,欢迎各位拍砖。
  
   最新版本iTextSharp.dll(version:5.0.4),若转换的文件中有中文字符时,转pdf后可能不显示中文字符,网上的解决方案很多,也可以查看iTextSharp的文档,提供了解决方案。以下下载文件中包含iTextSharp文档和Aspose的相关文档,还有一个Demo。
http://download.csdn.net/source/2654440
贴上一段Image转pdf的代码:

 class ImageToPdf : FileToPdf
    {
        private Document document = null;

        private string sourceFilePath = "";

        private System.Drawing.Imaging.ImageFormat imageFormat = null;

        public ImageToPdf(Document _document, string _sourceFilePath,System.Drawing.Imaging.ImageFormat _imageFormat)
        {
            document = _document;

            sourceFilePath = _sourceFilePath;

            imageFormat = _imageFormat;
        }

        public override void ConvertFile()
        {
            System.Drawing.Image sourceImg = null;

            iTextSharp.text.Image pdfImage = null;

            try
            {
                document.Open();

                sourceImg = System.Drawing.Image.FromFile(sourceFilePath);

                pdfImage = iTextSharp.text.Image.GetInstance(sourceImg, imageFormat);

                pdfImage.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

                float height = document.Top - document.TopMargin;
                //图片原始大小
                pdfImage.ScaleToFit(sourceImg.Width > document.Right ? document.Right : sourceImg.Width, sourceImg.Height > height ? height : sourceImg.Height);

                //pdfImage.ScaleToFit(document.Right ,height);

                document.Add(pdfImage);
            }