阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

文档在线预览的实现

145次阅读
没有评论

共计 9786 个字符,预计需要花费 25 分钟才能阅读完成。

最近在研究企业文档管理,这个是基本上所有企业都需要的软件,当然也是有很多种解决方案。对于企业文档来说,最基本的需求就是独立存储,共享。这种需求只需要建立一个 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.linuxidc.com/Linux/2016-12/138564.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计9786字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中