MS Office 없이 파일 탐색기에서 Word/Excel 파일 미리보기

MS Office 없이 파일 탐색기에서 Word/Excel 파일 미리보기

저는 대학교 강사입니다. 연구소에서는 MS Office 비용을 감당할 수 없기 때문에 WPS Office를 사용해야 합니다. 따라서 Windows 파일에서 미리 보기 창을 켠 후 Word/Excel 파일을 미리 볼 수 있는 Windows의 기본 기능이 손실되었습니다. 탐침. 지난 2일 동안 대체 파일 탐색기를 검색했지만 일부 공급업체가 미리 보기를 주장하더라도 Office 문서에 사용할 수 없거나 미리 보기 기능이 전혀 없습니다.

우리는 종종 Windows 파일 탐색기에서 파일을 클릭하거나 화살표 키를 사용하여 많은 단어 파일을 살펴보기 때문에 교수진에게 미리보기가 절실히 필요합니다.

효과적인 솔루션을 제안해주세요.

답변1

winforms 애플리케이션을 개발할 수 있기 때문에 다양한 솔루션으로 열심히 노력했습니다.

대부분이 무료가 아니어서 사용할 수 없었는데, pandoc 변환기가 도움이 되었지만 여전히 좋지 않았습니다.

그래서 저는 이미 무료인 Syncfusion 커뮤니티 에디션으로 옮겼습니다. 라이브러리에서는 모든 주요 워드 프로세서 기반 형식을 변환할 수 있으며 그 결과는 다른 무료 솔루션과 동일했습니다. 누군가 필요한 경우 여기에서 소스를 공유하고 있으며(Winforms 코드 숨김 파일) 이를 통해 모든 주요 워드 프로세싱 기반 형식(.doc, .docx, .rtf, .dot, .odt)을 미리 볼 수 있습니다. 지원되지만 누구나 이를 포함하도록 확장할 수 있습니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Microsoft.VisualBasic.FileIO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocToPDFConverter;
using Syncfusion.OfficeChart;
using Syncfusion.OfficeChartToImageConverter;
using Syncfusion.Pdf;
using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace DocPreViewerNew
{
    public partial class Form1 : Form
    {
        public ChromiumWebBrowser wb;
        List<string> AllFiles = new List<string>();
        List<string> AllNamesOnly = new List<string>();
        string SelectedFile;
        string NameOnly;
        int ResizeUnit = 40;
        string[] SourcePath;
        int PDFZoomUnit = 100;
        string XLPath = "";

        public Form1()
        {
            InitializeComponent();
            InitializeChromium();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.KeyPreview = true;
            //lbFiles.Width = Convert.ToInt32(this.Width * 0.23);
            //panel2.Location = new Point(lbFiles.Location.X +Convert.ToInt32(this.Width * 0.23)+5, panel2.Location.Y);
            //panel2.Width = Convert.ToInt32(this.Width*0.75);

            if (Properties.Settings.Default.PreviewMode.Equals("HTML")) rbHTML.Checked = true;
            else rbPDF.Checked = true;

            PDFZoomUnit = Convert.ToInt32(txtPDFZoom.Text.Trim());

           
        }

        private void lbFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {               
                PDFZoomUnit = Convert.ToInt32(txtPDFZoom.Text.Trim());
                wb.LoadUrl("about:blank"); lblFCount.Text = "";
                if (lbFiles.SelectedIndices.Count == 1)
                {
                    // Two string lists
                    SelectedFile = AllFiles[lbFiles.SelectedIndex];
                    NameOnly = AllNamesOnly[lbFiles.SelectedIndex];
                    lblFCount.Text = "File No: " + (lbFiles.SelectedIndex+1).ToString();

                    if (NameOnly.EndsWith(".docx") || NameOnly.EndsWith(".doc") || NameOnly.EndsWith(".rtf"))
                    {
                        //Loads the template document
                        WordDocument document = new WordDocument(SelectedFile, FormatType.Automatic);

                        if (rbHTML.Checked == true)
                        {
                            //Saves the document as Html file
                            document.Save(Environment.CurrentDirectory + "\\" + "output.html", FormatType.Html);
                            wb.LoadUrl(Environment.CurrentDirectory + "\\" + "output.html");
                        }
                        else
                        {
                            //Initializes the ChartToImageConverter for converting charts during Word to pdf conversion
                            document.ChartToImageConverter = new ChartToImageConverter();
                            //Sets the scaling mode for charts (Normal mode reduces the Pdf file size)
                            document.ChartToImageConverter.ScalingMode = ScalingMode.Normal;
                            //Creates an instance of the DocToPDFConverter - responsible for Word to PDF conversion
                            DocToPDFConverter converter = new DocToPDFConverter();
                            //Sets true to enable the fast rendering using direct PDF conversion.
                            converter.Settings.EnableFastRendering = true;
                            //Converts Word document into PDF document
                            PdfDocument pdfDocument = converter.ConvertToPDF(document);
                            //Saves the PDF file to file system
                            pdfDocument.Save(Environment.CurrentDirectory + "\\" + "output.pdf");
                            //Closes the instance of document objects
                            wb.LoadUrl(Environment.CurrentDirectory + "\\" + "output.pdf#zoom=" + PDFZoomUnit.ToString() + "&toolbar=0");
                            pdfDocument.Close(true);
                            //Closes the document 
                            document.Close();
                        }
                    }
                    else if (NameOnly.EndsWith(".pdf"))
                    {
                        wb.LoadUrl(SelectedFile + "#zoom=" + PDFZoomUnit.ToString() + "&toolbar=0");
                    }
                    else if (NameOnly.EndsWith(".txt"))
                        wb.LoadUrl(SelectedFile);
                    else
                    {
                        File.WriteAllText(Environment.CurrentDirectory + "\\" + "error1.html", "<h3>** Some Error **</h3><h4>Format not supported</h4>");
                        wb.LoadUrl(Environment.CurrentDirectory + "\\" + "error1.html");
                    }

                }
                else if (lbFiles.SelectedIndices.Count > 1)
                {
                    lblFCount.Text = "Total Selected: " + lbFiles.SelectedIndices.Count.ToString();
                }
            }
            catch(Exception ex)
            {
                File.WriteAllText(Environment.CurrentDirectory + "\\" + "error1.html", "<h3>** Some Error **</h3><h4>" + ex.Message + "</h4>");
                wb.LoadUrl(Environment.CurrentDirectory + "\\" + "error1.html");
            }

        }

        private void btnMoveSelected_Click(object sender, EventArgs e)
        {
           
        }



        //********
        #region UtilityFuntions


        private void lbFiles_DoubleClick(object sender, EventArgs e)
        {
            StartMaximized(AllFiles[lbFiles.SelectedIndex]);
        }

        private void lbFiles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartMaximized(AllFiles[lbFiles.SelectedIndex]);
            else if (e.KeyCode == Keys.Delete)
            {
                try
                {
                    if (lbFiles.SelectedIndex != -1)
                    {
                        var confirmResult = MessageBox.Show("Are you sure to delete this item ??", "Confirm Delete!!", MessageBoxButtons.YesNo);

                        if (confirmResult == DialogResult.Yes)
                        {
                            wb.LoadUrl("about:blank");
                            FileSystem.DeleteFile(AllFiles[lbFiles.SelectedIndex], UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                            AllFiles.RemoveAt(lbFiles.SelectedIndex);
                            AllNamesOnly.RemoveAt(lbFiles.SelectedIndex);
                            lbFiles.SelectedIndexChanged -= lbFiles_SelectedIndexChanged;
                            lbFiles.Items.RemoveAt(lbFiles.SelectedIndex);
                            lbFiles.SelectedIndexChanged += lbFiles_SelectedIndexChanged;
                        }
                    }
                }
                catch (OperationCanceledException) { }
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                RefreshEveryThing();
                btnXL.Enabled = true; btnMarks.Enabled = false;
                SourcePath = (string[])e.Data.GetData(DataFormats.FileDrop, false);
                

                if (SourcePath.Length == 1)
                {
                    XLPath = "";
                    AllFiles = Directory.GetFiles(SourcePath[0]).ToList();
                    string tmp = "";

                    foreach (string f in AllFiles)
                    {
                        tmp = f.Substring(f.LastIndexOf(@"\") + 1);
                        AllNamesOnly.Add(tmp);
                        lbFiles.Items.Add(tmp);
                    }
                    lbFiles.Sorted = true;

                    XLPath = SourcePath[0];
                }

            }
            catch { }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }


        private void StartMaximized(string FullFileName)
        {
            Process P = new Process();
            P.StartInfo.UseShellExecute = true;
            P.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            P.StartInfo.FileName = FullFileName;
            P.Start();
        }

        private void Sleeep(int s)
        {
            Thread.Sleep(TimeSpan.FromSeconds(s));
        }

        
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();

            if (rbPDF.Checked == true) Properties.Settings.Default.PreviewMode = "PDF";
            else Properties.Settings.Default.PreviewMode = "HTML";
            Properties.Settings.Default.Save();
        }

        private void btnDec_Click(object sender, EventArgs e)
        {
            Point p = panel2.Location;
            lbFiles.Width -= ResizeUnit;
            panel2.Location = new Point(p.X - ResizeUnit, p.Y);
            //lblFCount.Location = new Point(p.X - ResizeUnit, lbFiles.Location.Y);
            panel2.Width += ResizeUnit;

        }

        private void btnInc_Click(object sender, EventArgs e)
        {
            Point p = panel2.Location;
            lbFiles.Width += ResizeUnit;
            panel2.Location = new Point(p.X + ResizeUnit, p.Y);
            //lblFCount.Location = new Point(p.X + ResizeUnit, lbFiles.Location.Y);
            panel2.Width -= ResizeUnit;
        }

        private void RefreshEveryThing()
        {
            try
            {
                AllFiles.Clear();
                AllNamesOnly.Clear();
                lbFiles.Items.Clear();
                SourcePath = null;
                SelectedFile = "";
                NameOnly = "";

                wb.LoadUrl("about:blank");

                if (File.Exists(Environment.CurrentDirectory + "\\" + "output.html"))
                FileSystem.DeleteFile(Environment.CurrentDirectory + "\\" + "output.html", UIOption.OnlyErrorDialogs, RecycleOption.DeletePermanently);

                if (File.Exists(Environment.CurrentDirectory + "\\" + "output.pdf"))
                    FileSystem.DeleteFile(Environment.CurrentDirectory + "\\" + "output.pdf", UIOption.OnlyErrorDialogs, RecycleOption.DeletePermanently);

                //if (SourcePath!=null && SourcePath.Length == 1)
                //{
                //    AllFiles = Directory.GetFiles(SourcePath[0]).ToList();
                //    string tmp = "";

                //    foreach (string f in AllFiles)
                //    {
                //        tmp = f.Substring(f.LastIndexOf(@"\") + 1);
                //        AllNamesOnly.Add(tmp);
                //        lbFiles.Items.Add(tmp);
                //    }
                //}
            }
            catch { }
        }

        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            wb = new ChromiumWebBrowser("");

            // Add it to the form and fill it to the form window.
            this.panel2.Controls.Add(wb);
            wb.Dock = DockStyle.Fill;
        }


        #endregion

        private void btnMarks_Click(object sender, EventArgs e)
        {
            if (lbFiles.SelectedIndex != -1)
            {
                Marks frmMarks = new Marks();
                frmMarks.ID = lbFiles.SelectedItem.ToString();
                frmMarks.XLFILE = XLPath;
                frmMarks.ShowDialog();

                if (frmMarks.MARKSENTERED == true)
                    lblFCount.Text = "Marks entered successfully";
                else
                    lblFCount.Text = "**Problem entering Marks**";

                frmMarks.Close();
            }
        }

        private void btnXL_Click(object sender, EventArgs e)
        {
            HSSFWorkbook hssfwb=null;
            
            try
            {
                if (Directory.Exists(SourcePath[0]))
                {
                    OpenFileDialog XL = new OpenFileDialog();
                    if (XLPath != String.Empty) XL.InitialDirectory = XLPath;
                    XL.Title = "Select Marks Sheet File";
                    XL.Filter = "Excel Files|*.xls;*.xlsx";
                    if (XL.ShowDialog() == DialogResult.OK) XLPath = XL.FileName;

                    //Check old Excel File
                    if (XLPath.EndsWith(".xls"))
                    {
                        using (FileStream file = new FileStream(XLPath, FileMode.Open, FileAccess.Read))
                        {
                            hssfwb = new HSSFWorkbook(file);
                            file.Close();
                        }

                        ISheet sheet = hssfwb.GetSheetAt(0);
                        try
                        {
                            if (sheet.GetRow(0).GetCell(0).StringCellValue != "StudentId" || sheet.GetRow(0).GetCell(1).StringCellValue != "Marks" || sheet.GetRow(0).GetCell(2).StringCellValue != "Comments")
                            {
                                MessageBox.Show("First sheet must have these three columns:\n\nStudentId  Marks  Comments");
                            }
                            else btnMarks.Enabled = true;
                        }
                        catch (NullReferenceException) { MessageBox.Show("First sheet must have these three columns:\n\nStudentId  Marks  Comments"); }
                    }                   
                }
            }
            catch { }
            finally
            {
                if (hssfwb!=null) hssfwb.Close();
                btnXL.Enabled = !btnMarks.Enabled;
            }

                       
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.KeyCode == Keys.M)
            {
                btnMarks.PerformClick();
                //btncash_Click(null, null);
            }
        }
    } // Name space and class ends
}

관련 정보