[Asm] 纯文本查看 复制代码
namespace PrinterForm
{
partial class FrmMain
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.pnlTop = new System.Windows.Forms.Panel();
this.btnClear = new System.Windows.Forms.Button();
this.btnStart = new System.Windows.Forms.Button();
this.btnSelectDir = new System.Windows.Forms.Button();
this.txtOutputDir = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnSelectFiles = new System.Windows.Forms.Button();
this.dgvFiles = new System.Windows.Forms.DataGridView();
this.colFileName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colPath = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colStatus = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.pnlTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvFiles)).BeginInit();
this.SuspendLayout();
//
// pnlTop
//
this.pnlTop.BackColor = System.Drawing.SystemColors.Control;
this.pnlTop.Controls.Add(this.btnClear);
this.pnlTop.Controls.Add(this.btnStart);
this.pnlTop.Controls.Add(this.btnSelectDir);
this.pnlTop.Controls.Add(this.txtOutputDir);
this.pnlTop.Controls.Add(this.label1);
this.pnlTop.Controls.Add(this.btnSelectFiles);
this.pnlTop.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlTop.Location = new System.Drawing.Point(0, 0);
this.pnlTop.Name = "pnlTop";
this.pnlTop.Size = new System.Drawing.Size(884, 90);
this.pnlTop.TabIndex = 0;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(152, 12);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(100, 32);
this.btnClear.TabIndex = 5;
this.btnClear.Text = "清空列表";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnStart
//
this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnStart.BackColor = System.Drawing.Color.ForestGreen;
this.btnStart.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnStart.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnStart.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnStart.ForeColor = System.Drawing.Color.White;
this.btnStart.Location = new System.Drawing.Point(731, 12);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(141, 66);
this.btnStart.TabIndex = 4;
this.btnStart.Text = "开始转换";
this.btnStart.UseVisualStyleBackColor = false;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnSelectDir
//
this.btnSelectDir.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSelectDir.Location = new System.Drawing.Point(630, 51);
this.btnSelectDir.Name = "btnSelectDir";
this.btnSelectDir.Size = new System.Drawing.Size(75, 27);
this.btnSelectDir.TabIndex = 3;
this.btnSelectDir.Text = "选择...";
this.btnSelectDir.UseVisualStyleBackColor = true;
this.btnSelectDir.Click += new System.EventHandler(this.btnSelectDir_Click);
//
// txtOutputDir
//
this.txtOutputDir.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtOutputDir.Font = new System.Drawing.Font("宋体", 10F);
this.txtOutputDir.Location = new System.Drawing.Point(100, 52);
this.txtOutputDir.Name = "txtOutputDir";
this.txtOutputDir.ReadOnly = true;
this.txtOutputDir.Size = new System.Drawing.Size(524, 27);
this.txtOutputDir.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("宋体", 10F);
this.label1.Location = new System.Drawing.Point(12, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(93, 17);
this.label1.TabIndex = 1;
this.label1.Text = "输出目录:";
//
// btnSelectFiles
//
this.btnSelectFiles.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnSelectFiles.Location = new System.Drawing.Point(12, 12);
this.btnSelectFiles.Name = "btnSelectFiles";
this.btnSelectFiles.Size = new System.Drawing.Size(134, 32);
this.btnSelectFiles.TabIndex = 0;
this.btnSelectFiles.Text = "+ 添加文件";
this.btnSelectFiles.UseVisualStyleBackColor = true;
this.btnSelectFiles.Click += new System.EventHandler(this.btnSelectFiles_Click);
//
// dgvFiles
//
this.dgvFiles.AllowUserToAddRows = false;
this.dgvFiles.AllowUserToDeleteRows = false;
this.dgvFiles.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvFiles.BackgroundColor = System.Drawing.Color.White;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 10F);
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvFiles.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgvFiles.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvFiles.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colFileName,
this.colPath,
this.colStatus});
this.dgvFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgvFiles.Location = new System.Drawing.Point(0, 90);
this.dgvFiles.Name = "dgvFiles";
this.dgvFiles.ReadOnly = true;
this.dgvFiles.RowTemplate.Height = 27;
this.dgvFiles.Size = new System.Drawing.Size(884, 471);
this.dgvFiles.TabIndex = 1;
//
// colFileName
//
this.colFileName.DataPropertyName = "FileName";
this.colFileName.FillWeight = 30F;
this.colFileName.HeaderText = "文件名";
this.colFileName.Name = "colFileName";
this.colFileName.ReadOnly = true;
//
// colPath
//
this.colPath.DataPropertyName = "FullPath";
this.colPath.FillWeight = 50F;
this.colPath.HeaderText = "完整路径";
this.colPath.Name = "colPath";
this.colPath.ReadOnly = true;
//
// colStatus
//
this.colStatus.DataPropertyName = "Status";
this.colStatus.FillWeight = 20F;
this.colStatus.HeaderText = "状态";
this.colStatus.Name = "colStatus";
this.colStatus.ReadOnly = true;
//
// FrmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 561);
this.Controls.Add(this.dgvFiles);
this.Controls.Add(this.pnlTop);
this.MinimumSize = new System.Drawing.Size(600, 400);
this.Name = "FrmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "网页/MHT 转 PDF 工具";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMain_FormClosing);
this.pnlTop.ResumeLayout(false);
this.pnlTop.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvFiles)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel pnlTop;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnSelectDir;
private System.Windows.Forms.TextBox txtOutputDir;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnSelectFiles;
private System.Windows.Forms.DataGridView dgvFiles;
private System.Windows.Forms.DataGridViewTextBoxColumn colFileName;
private System.Windows.Forms.DataGridViewTextBoxColumn colPath;
private System.Windows.Forms.DataGridViewTextBoxColumn colStatus;
private System.Windows.Forms.Button btnClear;
}
}
using CefSharp.WinForms;
using CefSharp;
using System;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PrinterForm
{
public partial class FrmMain : Form
{
private ChromiumWebBrowser browser;
private BindingList<FileItem> fileList = new BindingList<FileItem>();
private bool isProcessing = false;
public FrmMain()
{
InitializeComponent();
InitializeChromium();
InitGrid();
}
private void InitializeChromium()
{
// 初始化 CefSharp 设置
if (!Cef.IsInitialized)
{
var settings = new CefSettings();
Cef.Initialize(settings);
}
// 初始化浏览器控件
browser = new ChromiumWebBrowser("about:blank");
browser.Size = new System.Drawing.Size(1024, 768); // 虚拟渲染尺寸
browser.Location = new System.Drawing.Point(-2000, -2000); // 移出可视区域
this.Controls.Add(browser);
}
private void InitGrid()
{
dgvFiles.AutoGenerateColumns = false;
dgvFiles.DataSource = fileList;
}
private void btnSelectFiles_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Multiselect = true;
ofd.Filter = "网页文件 (*.mht;*.mhtml;*.shtml;*.html)|*.mht;*.mhtml;*.shtml;*.html|所有文件 (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
foreach (var file in ofd.FileNames)
{
// 简单的去重检查
bool exists = false;
foreach (var item in fileList)
{
if (item.FullPath == file) exists = true;
}
if (!exists)
{
fileList.Add(new FileItem
{
FileName = Path.GetFileName(file),
FullPath = file,
Status = "等待中"
});
}
}
}
}
}
// 新增:清空列表按钮逻辑
private void btnClear_Click(object sender, EventArgs e)
{
if (isProcessing)
{
MessageBox.Show("正在处理中,无法清空列表。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (fileList.Count > 0)
{
if (MessageBox.Show("确定要清空所有文件吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
fileList.Clear();
}
}
}
private void btnSelectDir_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
txtOutputDir.Text = fbd.SelectedPath;
}
}
}
private async void btnStart_Click(object sender, EventArgs e)
{
if (isProcessing) return;
if (fileList.Count == 0)
{
MessageBox.Show("请先选择要转换的文件。");
return;
}
if (string.IsNullOrWhiteSpace(txtOutputDir.Text) || !Directory.Exists(txtOutputDir.Text))
{
MessageBox.Show("请选择有效的输出目录。");
return;
}
try
{
isProcessing = true;
// 禁用所有交互按钮
SetUIEnableState(false);
// 遍历处理
for (int i = 0; i < fileList.Count; i++)
{
var item = fileList[i];
// 如果已经是成功的,跳过,避免重复处理
if (item.Status == "成功") continue;
item.Status = "处理中...";
RefreshGridRow(i);
bool success = await ConvertSingleFileToPdf(item.FullPath, txtOutputDir.Text);
item.Status = success ? "成功" : "失败";
RefreshGridRow(i);
}
MessageBox.Show("所有任务执行完毕!");
}
finally
{
isProcessing = false;
// 恢复按钮状态
SetUIEnableState(true);
}
}
// 统一管理按钮状态
private void SetUIEnableState(bool enable)
{
btnStart.Enabled = enable;
btnSelectFiles.Enabled = enable;
btnSelectDir.Enabled = enable;
btnClear.Enabled = enable;
// 正在处理时变成灰色,反之恢复
btnStart.BackColor = enable ? System.Drawing.Color.ForestGreen : System.Drawing.Color.Gray;
}
private async Task<bool> ConvertSingleFileToPdf(string sourceFile, string outputDir)
{
try
{
string targetFileName = Path.GetFileNameWithoutExtension(sourceFile) + ".pdf";
string targetPath = Path.Combine(outputDir, targetFileName);
// 1. 异步等待页面加载完成
await LoadPageAsync(sourceFile);
// 给一点缓冲时间确保渲染(特别是MHT包含图片时)
await Task.Delay(500);
// 2. 生成 PDF
var pdfSettings = new PdfPrintSettings
{
PrintBackground = true, // 打印背景图
HeaderFooterEnabled = false, // 不要是页眉页脚
MarginType = CefPdfPrintMarginType.Default
};
bool result = await browser.PrintToPdfAsync(targetPath, pdfSettings);
return result;
}
catch (Exception ex)
{
Console.WriteLine($"转换异常: {ex.Message}");
return false;
}
}
private Task LoadPageAsync(string filePath)
{
var tcs = new TaskCompletionSource<bool>();
EventHandler<FrameLoadEndEventArgs> handler = null;
handler = (s, e) =>
{
if (e.Frame.IsMain)
{
browser.FrameLoadEnd -= handler;
tcs.TrySetResult(true);
}
};
browser.FrameLoadEnd += handler;
browser.Load(filePath);
return tcs.Task;
}
private void RefreshGridRow(int index)
{
if (index >= 0 && index < dgvFiles.Rows.Count)
{
dgvFiles.InvalidateRow(index);
Application.DoEvents();
}
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (isProcessing)
{
MessageBox.Show("任务正在进行中,请稍后再关闭。");
e.Cancel = true;
return;
}
Cef.Shutdown();
}
}
}