PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.com/

XPdfForm and DrawImage issue in C# PrintDialog printing
http://forum.pdfsharp.com/viewtopic.php?f=2&t=4722
Page 1 of 1

Author:  chase [ Wed Nov 13, 2024 8:47 pm ]
Post subject:  XPdfForm and DrawImage issue in C# PrintDialog printing

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();
}
}

Author:  TH-Soft [ Mon Nov 18, 2024 8:46 am ]
Post subject:  Re: XPdfForm and DrawImage issue in C# PrintDialog printing

PDFsharp cannot render PDF (see FAQ).
You cannot bypass that limitation, no matter how complicated your code looks.

DrawImage works for PDF only if the XGraphics object was created for a PDF page.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/