Я преподаватель в университете, мы вынуждены использовать WPS Office, так как институт не может нести расходы на MS Office, поэтому мы потеряли функцию по умолчанию в Windows для предварительного просмотра файлов Word/Excel после включения панели предварительного просмотра в проводнике Windows. Последние 2 дня я потратил на поиски альтернативного проводника, но даже если какой-то поставщик утверждает, что предварительный просмотр недоступен для офисных документов, или вообще не имеет функции предварительного просмотра.
Предварительный просмотр крайне необходим преподавателям, поскольку зачастую нам приходится просматривать множество текстовых файлов, просто щелкая по ним в проводнике Windows или используя клавиши со стрелками для навигации.
Пожалуйста, предложите какое-нибудь работающее решение.
решение1
Так как я умею разрабатывать приложения WinForms, я усердно пробовал разные решения.
Большинство из них были платными, поэтому их нельзя было использовать, тогда мне помог конвертер pandoc, но он был не очень хорош.
Поэтому я перешел на Syncfusion Community Edition, он уже бесплатный, и его библиотеки позволяют конвертировать все основные форматы на основе текстового процессора, и его результат был таким же, как и у других платных решений. Я делюсь исходным кодом здесь, если кому-то нужно (это файл с кодом Winforms), и он позволяет просматривать все основные форматы на основе текстового процессора (.doc, .docx, .rtf, .dot, .odt). Форматы Excel или ppt не поддерживаются, но любой может расширить его, включив и их.
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
}