I’m encountering an issue when trying to print a PDF file that opens correctly in Adobe Reader. When I select ‘Microsoft Print to PDF’ in the PrintDialog UI, the resulting PDF file is empty. I suspect the problem lies in the following code, particularly with the XPdfForm.FromFile(filePath) and DrawImage methods, which seem to fail to render the PDF page onto the print page. In detail, the pdfForm, line 3, does not have Format field value, it is null. Does the DrawImage need that information? I can't set the Format and the action is not allowed!
I am using PDFsharp-MigraDoc-GDI, v6.1.1. Any help will be appreciated.
public void PrintPdfXPdForm(string filePath) { // Load the PDF document XPdfForm pdfForm = XPdfForm.FromFile(filePath); // Check if the PDF form is loaded correctly if (pdfForm.PageCount == 0) { MessageBox.Show($"The PDF file could not be loaded or is empty.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
// Create a PrintDialog PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == DialogResult.OK) { // Create a PrintDocument PrintDocument printDocument = new PrintDocument(); printDocument.PrintPage += (sender, e) => { // Select the first page of the PDF pdfForm.PageNumber = 1;
// Calculate the scaling factor double scaleX = e.PageBounds.Width / pdfForm.PixelWidth; double scaleY = e.PageBounds.Height / pdfForm.PixelHeight; double scale = Math.Min(scaleX, scaleY);
// Calculate the position to center the PDF content double offsetX = (e.PageBounds.Width - pdfForm.PixelWidth * scale) / 2; double offsetY = (e.PageBounds.Height - pdfForm.PixelHeight * scale) / 2;
// Draw the PDF page onto the PrintDocument with scaling XGraphics gfx = XGraphics.FromGraphics(e.Graphics, new XSize(e.PageBounds.Width, e.PageBounds.Height), null); gfx.ScaleTransform(scale); gfx.DrawImage(pdfForm, offsetX / scale, offsetY / scale, pdfForm.PixelWidth, pdfForm.PixelHeight); };
// Set the printer settings printDocument.PrinterSettings = printDialog.PrinterSettings;
// Print the document printDocument.Print(); } }
|