文档在线预览的实现

简介:

最近在研究企业文档管理,这个是基本上所有企业都需要的软件,当然也是有很多种解决方案。对于企业文档来说,最基本的需求就是独立存储,共享。这种需求只需要建立一个Windows共享文件夹或者架一个Samba服务器即可实现,无法做复杂的权限管理,统计等。另一种方案就是架一个Web应用,比如SharePoint,就可以实现。

既然是WEB应用,进一步的需求是能够在线查看文档,根据用户需求可能不允许下载,不允许打印文档。这一点微软的高级解决方案是使用RMS,能够设置每个用户的打开权限,是否打印等,要求必须是域内,而且只管理Office文件的权限,对txt,pdf就没办法了。另外一个解决方案是在线文档预览,用户在网页中查看文档内容,用户无需拿到原始文档,如果有权限的话,可以允许用户下载文档。这就就是百度文库,豆丁之类的网站的功能。下面来说说怎么实现。

1.文档统一转换为pdf

这里的文档我们要看是什么格式,不同的格式有不同的转换方法。

1.1 Office文档转换pdf

对于Office文档(Word,Excel,PowerPoint),那么可以调用Office提供的COM接口,把文档另存为PDF。这个要求服务器上必须安装Office,同时要注意权限,不然很容易导致在本地调试时可以转换为PDF,但是一旦部署到服务器上去就不行。另外还需要注意的是,如果Office转换pdf时发生异常,可能导致Office的进程驻留在服务器,不断驻留Office进程会导致服务器资源耗尽。

这是Office文档转换为pdf的代码:

复制代码
///   <summary>  
///  将word文档转换成PDF格式 
///   </summary>  
///   <param name="sourcePath"></param>  
///   <param name="targetPath"></param>  
///   <returns></returns>  
public  static  bool ConvertWord2Pdf( string sourcePath,  string targetPath) 

     bool result; 
    Word.WdExportFormat exportFormat= Word.WdExportFormat.wdExportFormatPDF; 
     object paramMissing = Type.Missing; 
    Word.Application wordApplication =  new Word.Application(); 
    Word.Document wordDocument =  null
     try 
    { 
         object paramSourceDocPath = sourcePath; 
         string paramExportFilePath = targetPath;
        Word.WdExportFormat paramExportFormat = exportFormat; 
        Word.WdExportOptimizeFor paramExportOptimizeFor = 
                Word.WdExportOptimizeFor.wdExportOptimizeForPrint; 
        Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument; 
         int paramStartPage =  0
         int paramEndPage =  0
        Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent; 
        Word.WdExportCreateBookmarks paramCreateBookmarks = 
                Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; 
    
        wordDocument = wordApplication.Documents.Open( 
                 ref paramSourceDocPath,  ref paramMissing,  ref paramMissing, 
                 ref paramMissing,  ref paramMissing,  ref paramMissing, 
                 ref paramMissing,  ref paramMissing,  ref paramMissing, 
                 ref paramMissing,  ref paramMissing,  ref paramMissing, 
                 ref paramMissing,  ref paramMissing,  ref paramMissing, 
                 ref paramMissing);
         if (wordDocument !=  null
            wordDocument.ExportAsFixedFormat(paramExportFilePath, 
                    paramExportFormat,  false
                    paramExportOptimizeFor, paramExportRange, paramStartPage, 
                    paramEndPage, paramExportItem,  true
                     true, paramCreateBookmarks,  true
                     truefalse
                     ref paramMissing); 
        result =  true
    } 
     finally 
    { 
         if (wordDocument !=  null
        { 
            wordDocument.Close( ref paramMissing,  ref paramMissing,  ref paramMissing); 
            wordDocument =  null
        } 
         if (wordApplication !=  null
        { 
            wordApplication.Quit( ref paramMissing,  ref paramMissing,  ref paramMissing); 
            wordApplication =  null
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
     return result; 
}
///   <summary>  
///  将excel文档转换成PDF格式 
///   </summary>  
///   <param name="sourcePath"></param>  
///   <param name="targetPath"></param>  
///   <returns></returns>  
public  static  bool ConvertExcel2Pdf( string sourcePath,  string targetPath) 

     bool result; 
     object missing = Type.Missing; 
    Excel.XlFixedFormatType targetType= Excel.XlFixedFormatType.xlTypePDF; 
    Excel.Application application =  null
    Excel.Workbook workBook =  null
     try 
    { 
        application =  new Excel.Application(); 
         object target = targetPath; 
        workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, 
                missing, missing, missing, missing, missing, missing, missing, missing, missing);
        workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard,  truefalse, missing, missing, missing, missing); 
        result =  true
    } 
     catch 
    { 
        result =  false
    } 
     finally 
    { 
         if (workBook !=  null
        { 
            workBook.Close( true, missing, missing); 
            workBook =  null
        } 
         if (application !=  null
        { 
            application.Quit(); 
            application =  null
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
     return result; 
}
///   <summary>  
///  将ppt文档转换成PDF格式 
///   </summary>  
///   <param name="sourcePath"></param>  
///   <param name="targetPath"></param>  
///   <returns></returns>  
public  static  bool ConvertPowerPoint2Pdf( string sourcePath,  string targetPath) 

     bool result; 
    PowerPoint.PpSaveAsFileType targetFileType= PowerPoint.PpSaveAsFileType.ppSaveAsPDF; 
    PowerPoint.Application application =  null
    PowerPoint.Presentation persentation =  null
     try 
    { 
        application =  new PowerPoint.Application(); 
        persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); 
        persentation.SaveAs(targetPath, targetFileType, MsoTriState.msoTrue);
        result =  true
    } 
     catch 
    { 
        result =  false
    } 
     finally 
    { 
         if (persentation !=  null
        { 
            persentation.Close(); 
            persentation =  null
        } 
         if (application !=  null
        { 
            application.Quit(); 
            application =  null
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
     return result; 
复制代码

1.2 纯文本转换pdf

如果是文本需要转换为PDF,我们可以使用iTextSharp这个组件,对于纯文本,注意的是源文件中没有设置字体之类的,需要在转换成PDF时指定字体,否则对于中文可能由于没有设置字体而转换不出来。

复制代码
///   <summary>  
       
///  将Txt转换为PDF 
       
///   </summary>  
       
///   <param name="sourcePath"></param>  
       
///   <param name="targetPath"></param>  
       
///   <returns></returns>  
        public  static  bool ConvertText2Pdf( string sourcePath,  string targetPath) 
       { 
            var text = FileHelper.ReadTextFile(sourcePath); 
           Document document =  new Document(PageSize.A4);
            try 
           { 
                // step 2:创建一个writer用于监听Document以及通过PDF-stream指向一个文件  
               PdfWriter.GetInstance(document,  new FileStream(targetPath, FileMode.Create)); 
                //  step 3: 打开document  
               document.Open();
                var f = GetFont(); 
                //  step 4: 添加一段话到document中  
               document.Add( new Paragraph(text, f)); 
           } 
            catch (Exception ex) 
           { 
                return  false
           } 
            finally 
           { 
                if (document.IsOpen()) 
                    //  step 5: 关闭document  
                   document.Close(); 
           } 
            return  true
       }
        private  static Font GetFont() 
       { 
            var fontPath = ( string) ConfigurationManager.AppSettings[ " FontPath "]; 
            if ( string.IsNullOrEmpty(fontPath)) // 没有指定字体就用楷体 
           { 
                var fontName =  " 楷体 "
                if (!FontFactory.IsRegistered(fontName)) 
               { 
                   fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) +  @" \Fonts\simkai.ttf "
                   FontFactory.Register(fontPath); 
               } 
                return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 
           } 
           BaseFont bfChinese = BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 
           Font fontChinese =  new Font(bfChinese, 16f, Font.NORMAL); 
            return fontChinese; 
       } 
复制代码

1.3 HTML转换pdf

HTML中包含的元素较多,比较复杂,主要有两种方法,一种是调用浏览器的接口,让浏览器把HTML打印为PDF,另外就是ITextSharp提供了专门的XML/HTML转换组件:XML Worker,这个已经独立出来,不包含在ITextSharp中,需要单独下载。

复制代码
public  static  bool ConvertHtml2Pdf( string text,  string pdfPath) 
        { 
            Document document =  new Document(PageSize.A4);
             try 
            { 
                PdfWriter.GetInstance(document,  new FileStream(pdfPath, FileMode.Create)); 
                document.Open(); 
             
                 var fontName =  " 楷体 "
                 if (!FontFactory.IsRegistered(fontName)) 
                { 
                     var fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) +  @" \Fonts\simkai.ttf "
                    FontFactory.Register(fontPath); 
                } 
                 var elements = iTextSharp.tool.xml.XMLWorkerHelper.ParseToElementList(text,  @" body { 
    font-size: 16px; 
    color: #F00; 
    font-family: 楷体; 
}
"); 
                 // iTextSharp.text. 
                 foreach ( var element  in elements) 
                { 
                    document.Add(element); 
                }
            } 
             catch (DocumentException de) 
            { 
                Console.Error.WriteLine(de.Message); 
            } 
             catch (IOException ioe) 
            { 
                Console.Error.WriteLine(ioe.Message); 
            } 
            document.Close(); 
             return  true
        }
复制代码

1.4添加水印

以上都是转换成pdf的功能,在转换后,我们可以进一步使用ITextSharp对pdf进行加工,比较常见的添加水印功能。其实就是做一个淡淡的背景透明的图片,然后打开pdf文件,在每一页中画上水印图片即可。

复制代码
///   <summary>  
///  添加水印 
///   </summary>  
///   <param name="inputPath"> 源PDF文件路径 </param>  
///   <param name="outputPath"> 加水印后的PDF路径 </param>  
///   <param name="watermarkPath"> 水印图片的路径 </param>  
///   <param name="error"></param>  
///   <returns></returns>  
public  static  bool AddWatermark( string inputPath,  string outputPath,  string watermarkPath,  ref  string error) 

     try 
    { 
        PdfReader pdfReader =  new PdfReader(inputPath); 
         int numberOfPages = pdfReader.NumberOfPages; 
        FileStream outputStream =  new FileStream(outputPath, FileMode.Create); 
        PdfStamper pdfStamper =  new PdfStamper(pdfReader, outputStream); 
        PdfContentByte waterMarkContent;
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkPath);
        image.SetAbsolutePosition( 1010); 
         for ( int i =  1; i <= numberOfPages; i++) 
        { 
            waterMarkContent = pdfStamper.GetUnderContent(i); 
            waterMarkContent.AddImage(image); 
        } 
        pdfStamper.Close(); 
        pdfReader.Close(); 
        outputStream.Close(); 
         return  true
    } 
     catch (Exception ex) 
    { 
        error = ex.StackTrace; 
         return  false
    } 
复制代码

2.在线预览pdf文档

前面已经统一转换为pdf文档,接下来就是对pdf的在线预览。这个在以前是不现实的,现在有了HTML5,只要浏览器支持HTML5就可以使用pdf.js库,将服务器上的pdf文件转换成HTML5代码展示在浏览器上。另外还有一个解决方案是使用Flash,需要把pdf文件进一步转换为swf文件,然后由Flash播放器来播放这个文档。可惜Flash已经是一个过时即将淘汰的技术了,像iPad,iPhone就不支持Flash,所以使用HTML5才是更明智的选择。

pdf.js网站已经提供了库和示例,浏览页面是http://mozilla.github.io/pdf.js/web/viewer.html,我们要打开我们转换的文件,只需要在URL中添加参数即可:

/web/viewer.html?file=yourpdf.pdf

我们可以进一步修改viewer.html中的代码,根据需求去掉下载,打印等按钮,禁止用户下载和打印文件。

本文转自深蓝居博客园博客,原文链接:http://www.cnblogs.com/studyzy/p/5338398.html,如需转载请自行联系原作者

相关文章
|
6月前
Adoc文档的使用
Adoc文档的使用
26 0
|
7月前
|
前端开发
前端实现在线预览文档(pdf、doc文件)
前端实现在线预览文档(pdf、doc文件)
MarkDown编辑器-MarkText使用文档
1.Why MarkText typora要收费使用了,🤔我们可以使用免费的开源软件MarkText来编写MarkDown文档 MarkText官方承认,将会永远免费开源此软件 MarkText 是一个带有各种降价扩展的降价实时预览编辑器。您可以简单地编写和编辑文本 安装地址: MarkText安装
1106 0
MarkDown编辑器-MarkText使用文档
|
API Python
利用flasgger生成FlaskAPI文档
利用flasgger生成FlaskAPI文档
236 0
利用flasgger生成FlaskAPI文档
|
前端开发 JavaScript Apache
LESS文档
LESS文档
298 0
|
Java API Maven
jodconverter实现在线预览
现在预览是一个非常常用的供能。项目经理在会上提出必须实现改功能。首先博主先确定了一个思路:其他文档转成配pdf然后通过流发送到前台。因为前台支持pdf,可以直接预览。说干就干。下面上代码。
616 0
jodconverter实现在线预览
|
Web App开发 JavaScript 测试技术
实现在线预览PDF的几种解决方案
原文:实现在线预览PDF的几种解决方案 因客户需要实现PDF的预览处理,在网上找了一些PDF在线预览的解决方案,有的用PDFJS的在线预览方式,有的使用PDFObject的嵌入式显示,有的通过转换JPG/PNG方式实现间接显示的方式,开始是想通过简单的方式,能够使用JS插件实现预览最好,可是在线预览总是有一些不足,如不同浏览器的兼容问题,甚至不同的手机平台中展示的效果也不一样,不过最好还是采用了间接的方式,把PDF转换为图片展示效果,达到客户的要求。
6489 0
|
数据安全/隐私保护
|
XML JavaScript .NET