c# pdfium 打印机关闭对话框

问题描述 投票:0回答:1

我将使用 pdfium 库在后台进行自动 pdf 打印。通过API,它从数据库中找到pdf的路径并打印pdf。但在此之前,它会设置默认打印机。 (我通常选择Microsoft Print To PDF)。然后,当我单击“button1”时,它应该在后台自动打印,但我不断收到“将输出另存为”窗口。这会阻止它在后台自动执行此操作。我的目标是自动打印来自数据库的每个 pdf 文件。请帮我。谢谢大家。

由 DeepL.com 翻译(免费版)

-按钮所在部分和执行操作的代码-

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Drawing.Printing;
using PdfiumViewer;

namespace Printer
{
    public partial class UserControl3Faturalar : UserControl
    {
        private Timer _timer;

        public UserControl3Faturalar()
        {
            InitializeComponent();
        }

        private async void UserControl3Faturalar_Load(object sender, EventArgs e)
        {
            await LoadDataAsync();

            // Timer to refresh data every 2 minutes
            _timer = new Timer();
            _timer.Interval = 120000; // 2 minutes (120000 ms)
            _timer.Tick += async (s, args) => await LoadDataAsync();
            _timer.Start();
        }

        private async Task LoadDataAsync()
        {
            try
            {
                string baseUrl = ConfigReader.GetValue("url").TrimEnd('/');
                string userId = ConfigReader.GetValue("userId").Trim('/');
                string apiKey = ConfigReader.GetValue("x-api-key");

                string requestUrl = $"{baseUrl}/api/users/{userId}/pdfs";

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("x-api-key", apiKey);

                    HttpResponseMessage response = await client.GetAsync(requestUrl);
                    response.EnsureSuccessStatusCode();
                    string responseData = await response.Content.ReadAsStringAsync();

                    var dataList = JsonConvert.DeserializeObject<List<FaturaData>>(responseData);

                    dataGridView1.DataSource = dataList;
                    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                }
            }
            catch (HttpRequestException httpEx)
            {
                MessageBox.Show($"HTTP Error: {httpEx.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            string printerName = GlobalConfig.SelectedPrinter;
            if (string.IsNullOrEmpty(printerName))
            {
                MessageBox.Show("Please select a printer in the Yazicilar section.");
                return;
            }
            try
            {
                string baseUrl = ConfigReader.GetValue("url").TrimEnd('/');
                string userId = ConfigReader.GetValue("userId").Trim('/');
                string apiKey = ConfigReader.GetValue("x-api-key");

                string requestUrl = $"{baseUrl}/api/users/{userId}/pdfs";

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("x-api-key", apiKey);

                    HttpResponseMessage response = await client.GetAsync(requestUrl);
                    response.EnsureSuccessStatusCode();
                    string responseData = await response.Content.ReadAsStringAsync();

                    var pdfDataList = JsonConvert.DeserializeObject<List<FaturaData> (responseData);

                    foreach (var pdfData in pdfDataList)
                    {
                        if (File.Exists(pdfData.FilePath)) // Ensure the file exists
                        {
                            PrintControl.PrintPdf(pdfData.FilePath, printerName);
                            // MessageBox.Show($"Printing {pdfData.FilePath} complete.");
                        }
                        else
                        {
                            MessageBox.Show($"File not found: {pdfData.FilePath}");
                        }
                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                MessageBox.Show($"HTTP Error: {httpEx.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filePath = @"C:\Users\westinghouse\Desktop\Project1\C#\Printer\test.pdf";
            string printerName = "Microsoft Print To PDF"; // Yazıcı adı

            if (File.Exists(filePath))
            {
                try
                {
                    using (var document = PdfDocument.Load(filePath))
                    {
                        using (var printDocument = document.CreatePrintDocument())
                        {
                            printDocument.PrinterSettings.PrinterName = printerName;
                            printDocument.PrintController = new StandardPrintController()
                            printDocument.Print();

                            MessageBox.Show("Printing completed successfully.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Printing error: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show($"File not found: {filePath}");
            }
        }

    }

    public class FaturaData
    {
        public int ID { get; set; }
        public int UserID { get; set; }
        public string FilePath { get; set; }
        public int Pages { get; set; }
        public string Orientation { get; set; }
        public DateTime? CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public DateTime? DeletedAt { get; set; }
    }
}

印刷班

using System;
using System.Drawing.Printing;
using System.IO;
using PdfiumViewer;
using System.Windows.Forms;

public static class PrintControl
{
    public static void PrintPdf(string filePath, string printerName)
    {
        bool isSuccess = false;
        try
        {
            using (var document = PdfDocument.Load(filePath))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    printDocument.PrinterSettings.PrinterName = printerName;
                    printDocument.PrintController = new StandardPrintController(); // Dialogları devre dışı bırakır
                    printDocument.Print();
                    isSuccess = true;
                }
            }
        }
        catch (Exception ex)
        {
            // Hata durumunda mesajı kullanıcıya göster
            MessageBox.Show($"Printing error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        if (isSuccess)
        {
            // Başarı durumunda mesajı kullanıcıya göster
            MessageBox.Show($"Printing {filePath} complete.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

我尝试了一切方法来关闭对话框,但没有解决。我尝试了cutepdf打印机,对话再次打开。

c# printing printers pdfium
1个回答
0
投票

尝试设置以下内容:

printDocument.PrinterSettings.PrintToFile = true;
printDocument.PrinterSettings.PrintFileName = "file.pdf";
© www.soinside.com 2019 - 2024. All rights reserved.