I will do automatic pdf printing in the background using the pdfium library. with the api, it finds the path to the pdf from the database and prints the pdf. but before that, it sets a default printer. (I usually choose Microsoft Print To PDF). then when I click button1, it should print automatically in the background, but I keep getting the Save Output As window. this prevents it from doing it automatically in the background. my goal is to automatically print every pdf that comes instantly from the database. please help me. thank you everyone.
Translated with DeepL.com (free version)
-codes of the section where the button is located and the operation is performed-
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:UserswestinghouseDesktopProject1C#Printertest.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; }
}
}
printing class
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);
}
}
}
I tried everything to close the dialog but it was not solved. I tried the cutepdf printer and the dailog opened again.
Bilal Çobas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.