Alessandro Alessandro -4 years ago 576
C# Question

Print a PDF in C# with non standard size on a label printer

I create a PDF in a C# web application containing a label that has to be printed on a Dymo LabelWriter 450.

To create and print the label I am using Spire.PDF.

If I save the PDF in a folder and then print it using Acrobat Reader, it is printed correctly (and so I can confirm the page size set in my application is correct).

When I print directly from the application, the PDF is stretched abnormally, with reduced width and enlarged height, going beyond the boundaries of the label.

My code looks as follows:

PdfDocument doc = new PdfDocument();

SizeF pageSize = doc.Pages[0].Size;

PageSettings ps = new PageSettings();
ps.PaperSize = new PaperSize("MyPaperSize", (int)pageSize.Width, (int)pageSize.Height);

doc.PrintDocument.DefaultPageSettings = ps;

doc.PrinterName = printerName;

doc.PrintDocument.PrinterSettings.DefaultPageSettings.Margins.Left = 0;
doc.PrintDocument.PrinterSettings.DefaultPageSettings.Margins.Right = 0;
doc.PrintDocument.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
doc.PrintDocument.PrinterSettings.DefaultPageSettings.Margins.Bottom = 0;

PrintDocument printDoc = doc.PrintDocument;

Answer Source

I finally ended up using PdfiumViewer to open my document and create a PrintDocument to send to the printer.

The following code now prints correctly on my Dymo printer

PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrinterName = printerName;
printerSettings.DefaultPageSettings.PaperSize = paperSize;
printerSettings.DefaultPageSettings.Landscape = true;
printerSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);

PdfiumViewer.PdfDocument pdfiumDoc = PdfiumViewer.PdfDocument.Load(fileName);
PrintDocument pd = pdfiumDoc.CreatePrintDocument(PdfiumViewer.PdfPrintMode.CutMargin);             
pd.PrinterSettings = printerSettings;

I suppose the problem with the document being loaded by Spire.Pdf is that the DefaultPageSettings.PrintableArea (read only) has the wrong size and so the document eventually is compressed in that area.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download