吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 955|回复: 10
收起左侧

[其他求助] 各位大佬,求一个可以mhtml批量转pdf的软件

[复制链接]
gaoyinfei 发表于 2025-12-24 13:44
30吾爱币
各位大佬,求助一个可以将mhtml批量转pdf的软件,最好是mhtml ,mht ,都可以转换,susheng大佬的https://www.52pojie.cn/thread-1724528-1-1.html这个帖子里的软件可以将html转换成pdf,可惜不支持mhtml,mht我没有试过,估计也不支持,希望求一个此类的软件,最好是exe运行的。@susheng

最佳答案

查看完整内容

没有打安装文件,下面是代码: [mw_shl_code=asm,true]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(dis ...

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

freesaber 发表于 2025-12-24 13:44
没有打安装文件,下面是代码:
[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();
        }
    }
}


网盘:
链接:https://pan.baidu.com/s/1ZJWDrg5Jw9y9FJYBZilfLw?pwd=mgho
提取码:mgho

运行bin\x64\Release\PrinterForm.exe

可能需要下面依赖
● 依赖VC++ 2015-2019 Redistributable。下载地址:https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170
● 依赖.NETFramework,Version=v4.7.2。下载地址:https://dotnet.microsoft.com/zh-cn/download/dotnet-framework/thank-you/net472-web-installer

hbzy 发表于 2025-12-24 15:10
 楼主| gaoyinfei 发表于 2025-12-24 15:17

我要批量打印。不是几个,另外在线的也试过不好用。mhtml这个格式转不了,发生错误。也可以让pdf编辑软件,但都是合并成一个文件pdf文件,我要一个转一个的。
freesaber 发表于 2025-12-24 16:29
没有现成的。之前做过一个html面单打印的,使用的是C#。用CefSharp.ChromiumWebBrowser加载html,加载成功后,用browser.PrintToPdfAsync导出成pdf.
你这个需求用CefSharp这个组件就差不多了,选mhtml 、mht、html。然后,一个个加载,导出。

[C#] 纯文本查看 复制代码
&#65279;using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fleck;
using Microsoft.Win32;
using CefSharp;
using CefSharp.WinForms;
using System.Configuration;
using System.Drawing.Printing;
using System.IO;
using PdfiumViewer;

namespace PrinterForm
{
    public partial class frmPrinter : Form
    {
        private WebSocketServer server;
        private ChromiumWebBrowser browser;

        public frmPrinter()
        {
            InitializeComponent();
            InitializeChromium();
            this.Text = "快递面单打印组件";
        }

        private void InitializeChromium()
        {
            var settings = new CefSettings();
            Cef.Initialize(settings);
            browser = new ChromiumWebBrowser("about:blank")
            {
                Dock = DockStyle.Fill,
            };
            this.plBrowser.Controls.Add(browser);
        }

        private void StartWebSocket()
        {
            server = new WebSocketServer("ws://0.0.0.0:5597");
            server.Start(socket =>
            {
                socket.OnOpen = () => Console.WriteLine("Open!");
                socket.OnClose = () => Console.WriteLine("Close!");
                socket.OnMessage = message =>
                {
                    PrintHTML(message);
                };
            });
        }

        private void PrintHTML(string html)
        {
            // 取消之前的事件订阅
            browser.FrameLoadEnd -= OnFrameLoadEnd;

            // 获取用户输入的纸张尺寸并进行校验
            if (!ValidateDimensions(txtWidth.Text.Trim(), txtHeight.Text.Trim(), out double width, out double height))
            {
                // 如果校验失败,显示错误信息
                ShowError("请输入有效的纸张尺寸(宽度和高度必须为正数)。");
                return;
            }

            // 检查传入的html是否已经包含HTML标签
            if (!html.TrimStart().StartsWith("<!DOCTYPE html>", StringComparison.OrdinalIgnoreCase))
            {
                // 如果不包含HTML标签,添加HTML头部信息,确保使用UTF-8编码,并添加打印样式
                html = $@"
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset='UTF-8'>
                    <style>
                        [url=home.php?mod=space&uid=1953840]@page[/url] {{
                            size: {width}mm {height}mm;
                            margin: 0;
                        }}
                        html,body {{
                            margin: 0;
                            padding: 0;
                        }}
                    </style>
                </head>
                <body>{html}</body>
                </html>";
            }

            browser.LoadHtml(html);
            // 等待页面加载完成并调用打印
            browser.FrameLoadEnd += OnFrameLoadEnd;
        }

        private async void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            if (e.Frame.IsMain)
            {
                // 确保在主框架加载完成后调用打印方法
                var pdfPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pdf");
                var printToPdfSettings = new CefSharp.PdfPrintSettings
                {
                    //  true 表示打印背景图形,设置为 false 表示不打印背景图形。
                    PrintBackground = false,
                    // 表示打印页眉和页脚,设置为 false 表示不打印页眉和页脚。
                    DisplayHeaderFooter = false,
                    // 设置为 true 表示横向模式,设置为 false 表示纵向模式。
                    Landscape = false,
                    // 设置为 true 表示优先使用 CSS 定义的页面大小。默认为 false,在这种情况下内容将缩放以适应纸张大小。
                    PreferCssPageSize = true,
                    // 打印前缩放 PDF 的百分比(例如 0.5 表示 50%)。如果该值小于或等于零,将使用默认值 1.0。
                    // Scale = 1.8,
                    // 页边距类型。
                    MarginType = CefPdfPrintMarginType.Custom,
                    MarginTop = 0,
                    MarginBottom = 0,
                    MarginLeft = 0,
                    MarginRight = 0,
                };

                var success = await browser.PrintToPdfAsync(pdfPath, printToPdfSettings);

                if (success)
                {
                    PrintPdf(pdfPath);
                }
                else
                {
                    ShowError("面单生成PDF失败");
                }
            }
        }

        private void ShowError(string errorMessage)
        {
            string errorHtml = $@"
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset='UTF-8'>
                <style>
                    body {{
                        font-family: Arial, sans-serif;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        height: 100vh;
                        margin: 0;
                    }}
                    .error-message {{
                        color: red;
                        font-size: 20px;
                        text-indent: 2em;
                    }}
                </style>
            </head>
            <body>
                <div class='error-message'>{errorMessage}</div>
            </body>
            </html>";
            browser.LoadHtml(errorHtml);
        }

        private bool ValidateDimensions(string widthText, string heightText, out double width, out double height)
        {
            bool isValidWidth = double.TryParse(widthText, out width) && width > 0;
            bool isValidHeight = double.TryParse(heightText, out height) && height > 0;

            return isValidWidth && isValidHeight;
        }

        private void PrintPdf(string pdfPath)
        {
            // 获取用户输入的纸张尺寸,并转换为百分之一英寸
            int paperWidth = (int)(double.Parse(txtWidth.Text.Trim()) / 25.4 * 100);
            int paperHeight = (int)(double.Parse(txtHeight.Text.Trim()) / 25.4 * 100);

            using (var document = PdfiumViewer.PdfDocument.Load(pdfPath))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    // 设置自定义纸张尺寸
                    printDocument.DefaultPageSettings.PaperSize = new PaperSize("Custom", paperWidth, paperHeight);
                    printDocument.DocumentName = Path.GetFileName(pdfPath); ;
                    printDocument.PrintController = new StandardPrintController();

                    // 打印结束时删除文件
                    printDocument.EndPrint += (sender, e) =>
                    {
                        // 使用Task.Run将操作放到后台,避免阻塞UI线程
                        Task.Run(async () =>
                        {
                            try
                            {
                                // 等待3秒钟。这个时间通常足够打印机驱动程序完成对文件的读取。
                                // 您可以根据实际测试情况调整这个延迟时间。
                                await Task.Delay(3000);

                                // 延迟后,执行删除操作
                                File.Delete(pdfPath);
                            }
                            catch (Exception)
                            {
                                // 如果延迟后删除仍然失败(虽然可能性很小),则忽略异常。
                                // 因为打印任务已经提交,不应因此打扰用户。
                            }
                        });
                    };

                    try
                    {
                        printDocument.Print();
                    }
                    catch (Exception ex)
                    {
                        ShowError($"打印失败: {ex.Message}");
                    }
                }
                document.Dispose();
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfig();
            StartWebSocket();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveConfig();
            server.Dispose();
            server = null;
            Cef.Shutdown();
        }


        private void LoadConfig()
        {
            // 从AppSettings加载配置信息
            string txtWidth = ConfigurationManager.AppSettings["txtWidth"];
            string txtHeight = ConfigurationManager.AppSettings["txtHeight"];

            // 设置txtLeft和txtTop的文本内容
            this.txtWidth.Text = txtWidth;
            this.txtHeight.Text = txtHeight;
        }


        private void SaveConfig()
        {
            // 使用AppSettings保存配置信息
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["txtWidth"].Value = txtWidth.Text.Trim() == "" ? "75" : txtWidth.Text.Trim();
            config.AppSettings.Settings["txtHeight"].Value = txtHeight.Text.Trim() == "" ? "120" : txtHeight.Text.Trim();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}

免费评分

参与人数 2吾爱币 +2 热心值 +2 收起 理由
gaoyinfei + 1 + 1 热心回复!
liunianwen + 1 + 1 热心回复!

查看全部评分

 楼主| gaoyinfei 发表于 2025-12-24 17:00
freesaber 发表于 2025-12-24 16:29
没有现成的。之前做过一个html面单打印的,使用的是C#。用CefSharp.ChromiumWebBrowser加载html,加载成功 ...

感谢大佬 。能不能烦劳您搞成现成的软件,我程序搞不来。
freesaber 发表于 2025-12-24 17:18
gaoyinfei 发表于 2025-12-24 17:00
感谢大佬 。能不能烦劳您搞成现成的软件,我程序搞不来。

文件发一下,我有空了,搞一下
 楼主| gaoyinfei 发表于 2025-12-24 18:27
freesaber 发表于 2025-12-24 17:18
文件发一下,我有空了,搞一下

非常感谢。附上几个网页格式,谢谢。https://www.123865.com/s/F2GbVv-Omfod
 楼主| gaoyinfei 发表于 2025-12-25 12:14
freesaber 发表于 2025-12-25 09:34
没有打安装文件,下面是代码:
[mw_shl_code=asm,true]namespace PrinterForm
{

非常感谢大佬。已经成功。谢谢。
 楼主| gaoyinfei 发表于 2025-12-25 12:21
请问各位大神这个悬赏贴子怎样才能完结,并且转币。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-10-24 03:13

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表